Why isn't setAllSelected causing listbox.valueChange to emit? How can we ensure it emits?
import { Component, ViewChild } from '@angular/core';
import { CdkListbox, CdkOption } from '@angular/cdk/listbox';
/** @title Listbox with aria-activedescendant. */
@Component({
selector: 'cdk-listbox-activedescendant-example',
exportAs: 'cdkListboxActivedescendantExample',
templateUrl: 'cdk-listbox-activedescendant-example.html',
styleUrl: 'cdk-listbox-activedescendant-example.css',
standalone: true,
imports: [CdkListbox, CdkOption],
})
export class CdkListboxActivedescendantExample {
@ViewChild('listbox', { static: true, read: CdkListbox })
private listbox!: CdkListbox<any>;
...
ngOnInit() {
this.listbox.valueChange.subscribe((result) => {
console.log({ result });
});
this.listbox.setAllSelected(true);
console.log({ listboxInstance: this.listbox });
}
}
Under the hook of cdkOption:
So when you declare this.listBox.setAllselected(true) in ngOnit lifecycle-hooks, the value of options is still undefined and causing Cannot read properties of undefined.
When you move it into ngAfterViewInit, then the value is correctly defined, after Angular initializes the component's views, etc.
You need to wait for the view to be initialized before calling your setAllSelected method.