divyam
divyam

Reputation: 132

Default selected MatChips are not synced with MatChipList selected property

Default selected MatChips are not synced with MatChipList selected property Initial selected chips are empty eventhough Lime is selected. When we double click again Chip is getting added in selected but not initially. Demo here

Upvotes: 1

Views: 1062

Answers (1)

Quentin
Quentin

Reputation: 1933

I hope it will help you: 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);}
  }
}

DEMO:

enter image description here

Upvotes: 1

Related Questions