Am trying to set value to nested componenet which is added dynamically from json, but I could'nt acheieve it
What I Have Tried
Am creating a nested component inside another component, and setting a json value on a button click, am able to set the value for name, but not for the addressees and extra space object array
please help me to resolve this issue, sorry if this is a duplicated question
App.component.html
<div class="container">
<div class="row">
<div class="col-xs-12">
<div class="margin-20">
<h4>Add customer</h4>
</div>
<form [formGroup]="myForm" novalidate (ngSubmit)="save(myForm)">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" formControlName="name">
<small *ngIf="!myForm.controls.name.valid" class="text-danger">
Name is required (minimum 5 characters).
</small>
</div>
<!--addresses-->
<div formArrayName="addressees">
<div *ngFor="let address of myForm.controls.addressees.controls; let i=index" class="panel panel-default">
<div class="panel-heading">
<span>Address {{i + 1}}</span>
<span class="glyphicon glyphicon-remove pull-right" *ngIf="myForm.controls.addressees.controls.length > 1" (click)="removeAddress(i)"></span>
</div>
<div class="panel-body" [formGroupName]="i">
<address [group]="myForm.controls.addressees.controls[i]"></address>
</div>
</div>
</div>
<div class="margin-20">
<a (click)="addAddress()" style="cursor: default">
Add another address +
</a>
</div>
<div class="margin-20">
<button type="submit" class="btn btn-primary pull-right" [disabled]="!myForm.valid">Submit</button>
</div>
<div class="clearfix"></div>
<div class="margin-20">
<div>myForm details:-</div>
<pre>Is myForm valid?: <br>{{myForm.valid | json}}</pre>
<pre>form value: <br>{{myForm.value | json}}</pre>
</div>
</form>
</div>
</div>
</div>
App.Component.ts
export class AppComponent implements OnInit {
public myForm: FormGroup;
constructor(private _fb: FormBuilder) { }
ngOnInit() {
this.myForm = this._fb.group({
name: ['', [Validators.required, Validators.minLength(5)]],
addressees: this._fb.array([])
});
// add address
this.addAddress();
/* subscribe to addresses value changes */
// this.myForm.controls['addresses'].valueChanges.subscribe(x => {
// console.log(x);
// })
}
initAddress() {
return this._fb.group({
street: ['', Validators.required],
postcode: [''],
extraspaces: this._fb.array([])
});
}
addAddress() {
const control = <FormArray>this.myForm.controls['addressees'];
const addrCtrl = this.initAddress();
control.push(addrCtrl);
/* subscribe to individual address value changes */
// addrCtrl.valueChanges.subscribe(x => {
// console.log(x);
// })
}
removeAddress(i: number) {
const control = <FormArray>this.myForm.controls['addressees'];
control.removeAt(i);
}
save(model: Customer) {
// call API to save
// ...
console.log(model);
}
}