【问题标题】:How to add Angular Material auto complete in FormArray如何在 FormArray 中添加 Angular Material 自动完成
【发布时间】:2020-09-30 07:17:22
【问题描述】:

我正在使用 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)
    })
  );
}

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>

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

【问题讨论】:

  • 很多重要的代码丢失了——getControls()、orderItems、onAddItem() 是如何被触发的……最好是你创建了一个可以工作的 stackblitz 示例供我们使用,并发布所有的相关代码。

标签: angular angular-material angular-forms


【解决方案1】:

您需要将FormArray 中的每个control 与其自己的filteredOrderItems 数组相关联。 我回答了类似的问题here,请阅读答案详情,看看stackblitz复现。

请随时询问。 谢谢

【讨论】:

  • 非常感谢,这正是我想要的。
  • 不客气,我很高兴这是第一次有人将我的答案标记为正确^_^
【解决方案2】:

@Mukul Jaggi 你可以安装angular animation

我在 Stackblitz 上创建了一个演示。我希望这将对您/其他人有所帮助/指导。

npm install --save @angular/animations@6.0.5

【讨论】:

  • 谢谢,但我的主要问题是我无法对 itemName 和服务输入应用过滤器
猜你喜欢
  • 1970-01-01
  • 2016-10-11
  • 2017-07-29
  • 2020-01-11
  • 2023-03-23
  • 2021-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多