1
<mat-chip-list #list>
    <mat-chip *ngFor="let chip of chips">
    </mat-chip>
</mat-chip-list>

@ViewChild('list') list: MatChipList;

selectLastChip() {
  this.list._keyManager.setLastItemActive()
}

With Angular 14 it was possible to use keyManager with the MatChipList. Now with Angular 15 it is protected.

  • How to know which is the active chip?
  • How to know the index of the active chip?
  • How to set a chip to active?
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Mat
  • 113
  • 6
  • There is `` element which has a bindable property named `selected`, you can use it instead of `mat-chip` – Eldar Aug 28 '23 at 13:55
  • In Angular 14 it was possible to see the focused chip using this.list.chips.map(chip => chip.hasFocus), I'm looking for something similar. – Mat Aug 28 '23 at 15:30

1 Answers1

0

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.

Eldar
  • 9,781
  • 2
  • 10
  • 35