0

I would like fire the observable chipSelectionChanges, on init, in selecting a chip.

<mat-chip-list selectable multiple >
  <mat-chip
    *ngFor="let chipElement of chips"
    [selected]="chipElement.selected"
  >
    {{ chipElement.name | titlecase }}
  </mat-chip>
</mat-chip-list>

@ViewChild(MatChipList) matChipList!:MatChipList;
ngAfterViewInit() {
  this.matChipList.chipSelectionChanges.subscribe(console.log);
}

If chipElement.selected = true, I would like fire chipSelectionChanges.

How can I make ?

Dharman
  • 30,962
  • 25
  • 85
  • 135

2 Answers2

0

Generally ViewChild and ViewChildren queries are resolved completely in afterViewInit hook. For a better explanation of why see here

If you want to resolve queries before afterViewInit, preferably in onInit there is a flag to Viewchild decorator, static. Passing static true will resolve the queries before component is initialized completely. You you can access the value in onInit. Eg

@ViewChild(MatChipList, { static: false }) matChipList!:MatChipList;
ngAfterViewInit() {
  this.matChipList.chipSelectionChanges.subscribe(console.log);
}

Another hacky way would be to simply wrap the listener in setTimeOut like this

@ViewChild(MatChipList) matChipList!:MatChipList;
onInit() {
  this.matChipList.chipSelectionChanges.subscribe(console.log);
}

for complete explanation, see article here

Yousaf Raza
  • 703
  • 3
  • 11
  • I tried your solution, but i have this error : src_app_bar_bar_module_ts.js:2 ERROR TypeError: Cannot read properties of undefined (reading 'map') – Burckhardt Sébastien Sep 23 '22 at 21:46
  • SetTimeOut hacky works :) – Burckhardt Sébastien Sep 23 '22 at 22:42
  • Yeah, again. View child elements are properly initialized in afterviewInit. using static false does get the query resolved in onInit but some properties are still uninitialized and that is why settimeout works because it delays the execution of that call – Yousaf Raza Sep 24 '22 at 22:37
0

You should definitely listen to change Output directly from HTML.

<mat-chip-list selectable multiple (change)="yourFunction">
  <mat-chip
    *ngFor="let chipElement of chips"
    [selected]="chipElement.selected"
  >
    {{ chipElement.name | titlecase }}
  </mat-chip>
</mat-chip-list>

Typescript:

yourFunction(event: MatChipListChange ) {
  console.log(event);
}
Fabian Strathaus
  • 3,192
  • 1
  • 4
  • 26