默认选择的MatChips与MatChipList所选属性不同步

时间:2019-01-23 13:07:31

标签: angular angular-material2 md-chip

默认选择的 MatChips MatChipList 所选属性不同步 即使选择了Lime,初始选择的芯片还是空的。当我们再次双击时,会在 selected 中添加芯片,但不是最初添加的。 演示here

1 个答案:

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

演示:

enter image description here