[英]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.