My requirement is that I need to create a form with nested components. I am creating components for each form field means for textbox there will be one component, for radio
Same problem when trying to use a nested date picker. The solutions above didn't work for me for me. I solved the problem by emitting the date on change and by acessing the form conrol directly.
calendar-input.component.ts
@Component({
selector: 'app-calendar-input',
templateUrl: '...',
})
export class CalendarInputComponent {
@Output() dateChanged = new EventEmitter();
onClose() {
this.dateChanged.emit(this.currentDate);
}
...
}
The template
And the component with the form group and the form controls:
setFormControlValueByItem(item: FormItem, propName: string, value: any): void {
item.frameworkFormGroup.controls[propName].setValue(value);
item.frameworkFormGroup.controls[propName].markAsTouched();
item.frameworkFormGroup.controls[propName].markAsDirty();
}
item.frameworkFormGroup is in my case the instance of FormGroup and propName is the field name I would normall write to the attribute formControlName.
A disadvatage of this solution is that it makes the code less resistant against breaking chanches in the FormGroup and the FormConrol API in some cases.
See also: https://angular.io/api/forms/FormGroup and https://angular.io/api/forms/FormControl