簡體   English   中英

使用 ngFor 的材料芯片輸入 - 模板參考循環

[英]Material Chip Input with ngFor - template reference loop

我正在嘗試循環並動態創建材料芯片輸入,例如:

<section *ngFor="let basket of baskets">

<mat-form-field class="example-chip-list">
  <mat-chip-list #chipList aria-label="Fruit selection">
    <mat-chip *ngFor="let fruit of basket.fruits" [selectable]="selectable"
             [removable]="removable" (removed)="remove(basket, fruit)">
      {{fruit.name}}
      <mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
    </mat-chip>
    <input placeholder="New fruit..."
           [matChipInputFor]="chipList"
           [matChipInputSeparatorKeyCodes]="separatorKeysCodes"
           [matChipInputAddOnBlur]="addOnBlur"
           (matChipInputTokenEnd)="add(basket, $event)">
  </mat-chip-list>
</mat-form-field>

</section>

它不會真正起作用,因為這里使用了一個模板參考( #chipList ): [matChipInputFor]="chipList" ,我希望每個芯片輸入刪除/添加自己的項目。 由於模板引用是唯一的,它不會在*ngFor中工作。

我試過使用@ViewChildren

@ViewChildren(MatChipList) chipLists: QueryList<MatChipList>;

但我無法按 class 進行過濾,當我使用{ read: ElementRef }時 - 我需要保存 MatChipList 引用而不是元素引用。

知道什么是為每個basket動態循環和創建墊片輸入的理想方法嗎?

似乎您可以根據此處的答案那樣使用它。 可以使用表單控件處理這些值。 在我的例子中,我使用 chips 自動完成,然后我使用viewChildren來處理關閉

首先,輸入元素必須在 mat-chip-list 之外我認為這是您的代碼中的問題,因為 angular 默認情況下使用 *ngFor 等構建指令創建單獨的引用。

<section *ngFor="let basket of baskets">

<mat-form-field class="example-chip-list">
  <mat-chip-list #chipList aria-label="Fruit selection">
    <mat-chip *ngFor="let fruit of basket.fruits" [selectable]="selectable"
             [removable]="removable" (removed)="remove(basket, fruit)">
      {{fruit.name}}
      <mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
    </mat-chip>
  </mat-chip-list>

  <input placeholder="New fruit..."
           [matChipInputFor]="chipList"
           [matChipInputSeparatorKeyCodes]="separatorKeysCodes"
           [matChipInputAddOnBlur]="addOnBlur"
           (matChipInputTokenEnd)="add(basket, $event)">
</mat-form-field>

</section>

請參考此演示,單擊控制台分別引用每個模板引用,即使它們使用相同的名稱聲明: stackblitz

控制台將顯示差異如下: 在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM