I'm using Angular 8 Nested Reactive Form in a child component, but it does not work. I have searched the official Angular documentation, but I can not find any example on this.
My solution is available at stackblitz.com. I'm unable to show companyName for each company and address details for each address. Any ideas?
According to Kara Ericksons talk about “Angular Forms” at the Angular Connect 2017 it should be straight forward...
Her video Nested Forms in Angular between 35:31-36:51
In parent.component.html
<form [formGroup]="form">
<div *ngFor="let address of addresses">
<app-child [address]="address"></app-child>
</div>
<button type="submit">Save</button>
</form>
In parent.component.ts
export class ParentComponent implements OnInit {
form = new FormGroup({});
addresses : Address[] = [
new Address("Street 1", "City 1"),
new Address("Street 2", "City 2"),
new Address("Street 3", "City 3"),
]
constructor() { }
ngOnInit() {
}
}
In child.component.html
<div formGroupName="address">
<input formControlName="street">
<input formControlName="city">
</div>
In child.component.ts
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.less']
})
export class ChildComponent implements OnInit {
@Input() address: Address;
form: FormGroup;
constructor(parent: FormGroupDirective) {
this.form = parent.form;
}
ngOnInit() {
this.form.addControl('address', new FormGroup({
street: new FormControl()
city: new FormControl()
}));
}
}