I am using Angular 6. My form has a formArray
to which I Add Items on a button click.
My form looks like
private initForm() {
this.orderForm = new FormGroup({
'orderItems': this.orderItems,
'customerContact': new FormControl(null),
'totalAmount': new FormControl(null)
});
}
onAddItem() {
(<FormArray>this.orderForm.get('orderItems')).push(
new FormGroup({
'itemName': new FormControl(null, Validators.required),
'itemService': new FormControl(null, Validators.required),
'itemPrice': new FormControl(null)
})
);
}
Html code
<tbody formArrayName="orderItems">
<tr *ngFor="let orderItem of getControls(); let i = index" [formGroupName]="i">
<td>
<input type="text" formControlName="itemName" class="form-control" [matAutocomplete]="autoName">
<mat-autocomplete #autoName="matAutocomplete">
<mat-option *ngFor="let option of filteredOrderItems | async" [value]="option">
{{option}}
</mat-option>
</mat-autocomplete>
</td>
<td>
<input type="text" formControlName="itemService" class="form-control" [matAutocomplete]="autoService">
<mat-autocomplete #autoService="matAutocomplete">
<mat-option *ngFor="let option of filteredOrderServices | async" [value]="option">
{{option}}
</mat-option>
</mat-autocomplete>
</td>
<td>
<input class="form-control" type="text" formControlName="itemPrice" (keyup)="findTotal()">
<!-- </mat-form-field> -->
</td>
<td><button type="button" class="btn btn-danger" (click)="onDeleteIngredient(i)">Delete</button></td>
</tr>
</tbody>
Autocomplete on fileds itemName
and itemService
is not working. I am not able to apply filter to these fields. I am open to suggestions even if I am able to achieve this by changing some functionality of the form.
Here is the part of the application Stackblitz
clear()linkRemove all controls in the FormArray .
Binding FormArray to Template Inside the div use ngFor to loop through each element of skills FormArray. let i=index will store the index value of the array in template local variable i . We will make use of it to remove the element from the skills array. Each element under the skills is a FormGroup .
The FormArray is a way to Manage collection of Form controls in Angular. The controls can be FormGroup, FormControl, or another FormArray. Because it is implemented as Array, it makes it easier dynamically add controls.
You need to relate each control
inside the FormArray
to its own filteredOrderItems
array.
I answered a similar question here, please read the answer details and take a look at stackblitz reproduction.
please feel free to ask. Thanks
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With