4

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

Pieter Buys
  • 1,280
  • 1
  • 10
  • 20

1 Answers1

2

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.

Pieter Buys
  • 1,280
  • 1
  • 10
  • 20
  • 1
    I was also expecting to reference the panel right after responding to the (opened) event. Instead of relying on a timer, I used ngDoCheck to check for the reference. – David Morissette Feb 19 '21 at 03:33
  • Ok, just in case it helps someone else, in order to access the "async" result list using `ViewChild` along with the autocomplete reference does the job; for example at the `blur` event I am to do something like `this.autocomplete.options.find(element => element.value === eventValue);` and here it goes the api for it : https://material.angular.io/components/autocomplete/api – angellica.araujo Dec 27 '21 at 11:13