1

默认选择的MatChip不与MatChipList selected 属性同步 即使选择了 Lime,初始选择的芯片也是空的。当我们再次双击时,Chip 被添加到选中但不是最初。演示在这里

4

1 回答 1

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);}
  }
}

演示:

在此处输入图像描述

于 2019-01-24T14:12:11.640 回答