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 ?
CodePudding user response:
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
CodePudding user response:
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);
}