1

I'm trying to create a custom select/combobox element using the Angular Material CdkListbox so that the select/comobox dropdown can have keyboard navigation like native browser selects. I need to access the CdkListbox in the corresponding .ts file and call the methods I need.

How do I reference the cdkListbox in the corresponding ts file in order to use the methods as listed on angular material cdk docs

<ul
   cdkListbox
   class="w-full max-h-56 h-full overflow-x-hidden overflow-y-auto"
   data-simplebar>
   <app-select-item
   appSelectItem
   *ngFor="let item of items"
   [item]="item"
   [cdkOption]="item"
   [selected]="item.id === selectedItem!.id"
   (emit-selected-item)="setSelectedItem($event)></app-select-item>
rnxfod
  • 907
  • 2
  • 8
  • 14

1 Answers1

1

.html

   <ul
     cdkListbox
     #listbox <--your reference
     class="w-full max-h-56 h-full overflow-x-hidden overflow-y-auto"
     data-simplebar>
       <app-select-item
         appSelectItem
         *ngFor="let item of items"
         [item]="item"
         [cdkOption]="item"
         [selected]="item.id === selectedItem!.id"
         (emit-selected-item)="setSelectedItem($event)">
       </app-select-item>
    </ul>

.ts

class Component implements OnInit {
    ...
    @ViewChild('listbox', {static: true, read: CdkListbox}) // reference lookup
    private listbox!: CdkListbox<YourType>;
    ...
    ngOnInit() {
      console.log(this.listbox);
    }
}
Maxime Lyakhov
  • 140
  • 1
  • 11
  • If you want to access `ViewChild` in the component .ts file, you need to use `ngAfterViewInit` instead of `ngOnInit` https://stackoverflow.com/questions/56958219/viewchild-not-initializing-during-ngoninit/56958379#56958379 – Harun Yilmaz Apr 17 '23 at 13:38
  • 1
    @HarunYilmaz if the element is not hidden by structural directives, you can point it with ```static: true``` in decorator arguments. With this config you can access your ```@ViewChild``` in ```ngOnInit``` already – Maxime Lyakhov Apr 17 '23 at 14:38
  • Ah, you're right! I didn't pay attention to this nuance. Thanks! – Harun Yilmaz Apr 17 '23 at 14:48