Angular Material - mat-autocomplete未在ArrayForm中填充



这是一个复杂的形式,所以请忍受我,我会尽量回答你所有的疑问,让它工作。
我正试图实现我的表单自动完成,其中有formArray和formGroup。我在formarray外部和formarray内部的两个地方都有自动完成功能。
对于formarray外部的自动完成,我已经成功地实现了该功能,但对于formarray内部的自动完成,我有问题。
当我重新加载页面时,自动完成组件内没有加载数据,我得到以下错误。[![错误][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>

组件代码

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.stack.imgur.com/Gw3Wf.gif
[2]: https://i.stack.imgur.com/ZhoTN.gif

从我对这个SO的评论来看,如果我们需要知道索引,因为我们在函数中创建formGroup和订阅,我们可以使用"index"。这是另一个SO。

你可以,例如传递"index"到"搜索产品"功能;或者使用管道。添加群组时轻按

addProductGroup(index) {
...
this.productList$[index] = group.get("product_name").valueChanges.pipe(
tap(_=>this.index=index),  //<--store in a variable "index" the index of
//   the autocomplete we are changed
debounceTime(300),
//or pass to the function search_Products
switchMap(value => this.productService.search_Products(value,index))
);
}

最新更新