[英]Material Chip Input with ngFor - template reference loop
I'm trying to loop and create Material chip inputs dynamically, eg:我正在尝试循环并动态创建材料芯片输入,例如:
<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>
It's not really going to work since there is a template reference ( #chipList
) which is used here: [matChipInputFor]="chipList"
and I want each chip input to remove/add its own items.它不会真正起作用,因为这里使用了一个模板参考( #chipList
): [matChipInputFor]="chipList"
,我希望每个芯片输入删除/添加自己的项目。 Since template reference is unique, it won't work inside an *ngFor
.由于模板引用是唯一的,它不会在*ngFor
中工作。
I've tried to use @ViewChildren
:我试过使用@ViewChildren
:
@ViewChildren(MatChipList) chipLists: QueryList<MatChipList>;
but I'm unable to filter by class, and when I do use { read: ElementRef }
- I need to save the MatChipList reference and not the element ref.但我无法按 class 进行过滤,当我使用{ read: ElementRef }
时 - 我需要保存 MatChipList 引用而不是元素引用。
Any idea of what is the ideal way to loop and create those mat chip inputs dynamically for each basket
?知道什么是为每个basket
动态循环和创建垫片输入的理想方法吗?
Seems you can use it like that based on the answer here .似乎您可以根据此处的答案那样使用它。 The values can be handled using the form controls.可以使用表单控件处理这些值。 In my case, I had autocomplete with the chips which I then used viewChildren
to handle closing在我的例子中,我使用 chips 自动完成,然后我使用viewChildren
来处理关闭
First the input element must be outside the mat-chip-list I think this is the issue in your code because angular create separated references by default with building directives like *ngFor.首先,输入元素必须在 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>
Please refer to this demo on click the console reference each template-ref separately even they declared with same name: stackblitz请参考此演示,单击控制台分别引用每个模板引用,即使它们使用相同的名称声明: stackblitz
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.