默认选择的 MatChips 与 MatChipList 所选属性不同步 即使选择了Lime,初始选择的芯片还是空的。当我们再次双击时,会在 selected 中添加芯片,但不是最初添加的。 演示here
答案 0 :(得分:1)
我希望它能对您有所帮助:StackBlitz HERE
HTML:
<mat-chip-list #chipList multiple="true">
<mat-chip *ngFor="let fruit of fruits" [value]="fruit.name" [selected]="fruit.selected" (click)="onSelectFruit(fruit)">
{{fruit.name}}
</mat-chip>
</mat-chip-list>
<div class="hintLabel">Select Fruits</div>
<br/>
<button (click)="getSelectedChips()">Get Selected Chips</button>
<br/><br/>
<b>Selected Chips:</b>{{array | json}}<br/><br/>
<b>Dynamic Selected Chips:</b>{{arrayDynamic | json}}
TS:
array: Fruit["name"][] = [];
arrayDynamic: Fruit["name"][] = [];
ngOnInit(){
for (let fruit of this.fruits) {
if(fruit.selected){this.arrayDynamic.push(fruit.name);}
}
}
onSelectFruit(fruit){
fruit.selected=!fruit.selected
this.arrayDynamic = [];
for (let fruit of this.fruits) {
if(fruit.selected){this.arrayDynamic.push(fruit.name);}
}
}
getSelectedChips() {
this.array = [];
for (let fruit of this.fruits) {
if(fruit.selected){this.array.push(fruit.name);}
}
}
演示: