I am encountering an issue when trying to access the products array that is located within opticanOrders
inside the orderForm
. Despite seeing in the console that I should reference the products array like this:
orderForm.controls.opticianOrders.controls.products.controls
It does not seem to be working.
This is my component:
constructor(private customerService: CustomerService, private fb: FormBuilder) { }
orderForm: FormGroup;
ngOnInit() {
this.orderForm = this.fb.group({
name: [''],
surName: [''],
opticianOrders: this.fb.group({
orderDescription: [''],
products: this.fb.array([
this.initProduct()
])
}),
});
}
save(model: Customer) {
// call API to save customer
console.log(model);
}
onCancel(form: NgForm){
this.createState.emit(false);
}
initProduct(){
return this.fb.group({
name: [''],
manufacturerName: ['']
})
}
addProduct(){
const control = <FormArray>this.orderForm.controls['products'];
control.push(this.initProduct());
}
removeProduct(i: number){
const control = <FormArray>this.orderForm.controls['products']
}
Html
<form [formGroup]="orderForm" novalidate (ngSubmit)="save(orderForm)">
<!-- name -->
<div class="form-group">
<label>Name</label>
<input type="text" formControlName="name">
</div>
<!-- surName -->
<div class="form-group">
<label>Last Name</label>
<input type="text" formControlName="surName">
</div>
<div formGroupName="opticianOrders" class="form-group">
<label>Order Description</label>
<input type="text" formControlName="orderDescription">
</div>
<div formArrayName="products">
<div *ngFor="let product of orderForm.controls.opticianOrders.controls.products.controls; let i=index">
<div>
<span>Address {{i + 1}}</span>
<span *ngIf="orderForm.controls.opticianOrders.controls.products.controls.length > 1"
(click)="removeProduct(i)">
</span>
</div>
<div [formGroupName]="i">
<div>
<label>Product name</label>
<input type="text" formControlName="name">
</div>
</div>
</div>
</div>
<button type="submit" [disabled]="!orderForm.valid">Submit</button>
</form>