This is how you can select chips programmatically without fiddling with library internals :
template
<mat-chip-listbox class="mat-mdc-chip-set-stacked" aria-label="Color selection">
<mat-chip-option
*ngFor="let chip of availableColors"
[selected]="chip.selected"
(selectionChange)="selectionChanged($event,chip)"
[color]="chip.color"
>
{{chip.name}}
</mat-chip-option>
</mat-chip-listbox>
<hr />
<div>
<button (click)="selectRandom()">Select Randomly</button>
<button (click)="getSelected()">Get selected chips</button>
</div>
Component
export class ChipsStackedExample {
availableColors: ChipColor[] = [
{ name: 'none', color: undefined, selected: false },
{ name: 'Primary', color: 'primary', selected: false },
{ name: 'Accent', color: 'accent', selected: false },
{ name: 'Warn', color: 'warn', selected: false },
];
selectRandom() {
const ix = Math.floor(Math.random() * this.availableColors.length);
this.availableColors.forEach((r) => (r.selected = false));
this.availableColors[ix].selected = true;
console.log('selected', ix);
}
getSelected() {
const selected = this.availableColors.filter((r) => r.selected);
console.log('selected', selected);
const selectedIndexes = selected.map((r) =>
this.availableColors.indexOf(r)
);
console.log('indexes', selectedIndexes);
}
selectionChanged(e: MatChipSelectionChange, chip: ChipColor) {
chip.selected = e.selected;
console.log('selected chip', chip);
}
}
Stackblitz
Sad part of it you can not bind selected
property in two-way binding.