javascriptangularangular-materialmat-autocomplete

How do I get the Panel ElementRef of Mat Autocomplete


According to the MatAutocomplete documentation, there is a panel property on MatAutocomplete class that will give you the panel's elementRef.

panel: ElementRef

Element for the panel containing the autocomplete options.

I am struggling to get this to work though as the autocomplete.panel is always undefined? What am I missing?

<mat-autocomplete #auto="matAutocomplete">
  @ViewChild("auto") autocomplete: MatAutocomplete;

  ngAfterViewInit(): void {
    console.log(this.autocomplete.panel); // undefined??
  }

Stackblitz


Solution

  • I realized that the element will only be available when the panel is open and the element is in the DOM. Which makes sense if you think about it...

    See my updated stackblitz to see what I mean. Take note that the element is not yet added to the view on the (opened) event. Which means you will have to add a setTimeout or somehow wait for the element to be added to the dom before you can access it.