It is a complex form so please bear with me and I will try to answer all your doubts to get it working.
I am trying to implement mat-autocomplete for my form which has formArray and formGroup. I have autocomplete in 2 places outside the formarray and inside the formarray.
For the autocomplete outside the formarray I have successfully implemented the feature but for the autocomplete inside the formarray I have issues.
I get the below error when I reload the page and no data is loaded inside the autocomplete component. [![error][1]][1]
<div formArrayName="rawmaterialwh">
<div [formGroupName]="i" *ngFor="let product of products.controls; let i=index">
<legend>{{i+1}}</legend>
<div fxLayout="column">
<div fxLayout="row wrap" fxLayoutAlign="space-between center">
<div fxFlex.gt-sm="49" fxFlex.gt-xs="49" fxFlex="100" fxFlex.gt-md="49">
<mat-form-field attr.for="{{'rawmaterialid' + i}}" class="full-wid mrgn-b-lg">
<mat-label>{{'Raw Material'|translate}}</mat-label>
<input type="text" matInput formControlName="rawmaterialid" [matAutocomplete]="rawMaterialAutocomplete" />
<mat-autocomplete autoActiveFirstOption #rawMaterialAutocomplete="matAutocomplete"
[displayWith]="showRawMaterialName.bind(this)" (selectionChange)="onProductValueChange($event,i)">
<mat-option disabled selected hidden>{{'Raw Material'|translate}}</mat-option>
<mat-option *ngFor="let product_mode of filteredRawMaterial | async" [value]="product_mode.rawmaterialid">{{product_mode.name}}</mat-option>
</mat-autocomplete>
<mat-error *ngIf="products.controls[i].get('rawmaterialid').hasError('required')"> {{'Select Raw Material'|translate}} </mat-error>
</mat-form-field>
<!-- <mat-form-field attr.for="{{'rawmaterialid' + i}}" class="full-wid mrgn-b-lg">
<mat-label>{{'Raw Material'|translate}}</mat-label>
<mat-select formControlName="rawmaterialid" (selectionChange)="onProductValueChange($event,i)">
<mat-option disabled selected hidden>{{'Raw Material'|translate}}</mat-option>
<mat-option *ngFor="let product_mode of productOption"
[value]="product_mode.rawmaterialid">{{product_mode.name}}</mat-option>
</mat-select>
<mat-error *ngIf="products.controls[i].get('rawmaterialid').hasError('required')"> {{'Select Raw Material'|translate}} </mat-error>
</mat-form-field> -->
</div>
Component code
ngOnInit(): void {
this.filteredRawMaterial = this.form.controls.rawmaterialwh.get('rawmaterialid').valueChanges
.pipe(
tap(value => console.log('value in tap ', value)),
startWith(''),
map(value => this._filterRawMaterial(value))
);
}
[![form][2]][2]
[1]: https://i.sstatic.net/Gw3Wf.gif
[2]: https://i.sstatic.net/ZhoTN.gif
FormArray? There's noformArrayNamein your template andformControlNameshould be bound toirawmaterialid? And why are you looping throughproducts.controlsif your FormArray is calledrawmaterialwh? Would you share the code where you're initializing the form?get products(): FormArray { return this.form.get('rawmaterialwh') as FormArray; }