如何在 FormArray 中添加 Angular Material 自动完成

Muk*_*ggi 5 angular-material angular angular-forms

我正在使用 Angular 6。我的表单有一个formArray我在单击按钮时添加项目的表单。我的表格看起来像

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)
    })
  );
}
Run Code Online (Sandbox Code Playgroud)

html代码

<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>
Run Code Online (Sandbox Code Playgroud)

对文件自动完成itemName并且itemService不起作用。我无法对这些字段应用过滤器。即使我能够通过更改表单的某些功能来实现这一点,我也愿意接受建议。这是应用程序Stackblitz的一部分

Fur*_*oud 6

您需要将control里面的每个FormArray与它自己的filteredOrderItems数组相关联。我在这里回答了一个类似的问题,请阅读答案详细信息并查看stackblitz复制。

请随时询问。谢谢