Saturday, October 5, 2019

Error: Attempting to open an undefined instance of `mat-autocomplete`

Hi Guys ,

In this blog I will share information related to error :
Error: Attempting to open an undefined instance of `mat-autocomplete`

You may find this error when you use autocomplete in angular material .

The full error log is as follows :

AutocompleteSimpleExample.html:3 ERROR Error: Attempting to open an undefined instance of `mat-autocomplete`. Make sure that the id passed to the `matAutocomplete` is correct and that you're attempting to open it after the ngAfterContentInit hook.
    at getMatAutocompleteMissingPanelError (autocomplete-trigger.ts:99)
    at MatAutocompleteTrigger._attachOverlay (autocomplete-trigger.ts:615)
    at MatAutocompleteTrigger._handleFocus (autocomplete-trigger.ts:458)
    at Object.eval [as handleEvent] (VM548 AutocompleteSimpleExample.ngfactory.js:114)
    at handleEvent (view.ts:138)
    at callWithDebugContext (services.ts:630)
    at Object.debugHandleEvent [as handleEvent] (services.ts:377)
    at dispatchEvent (util.ts:135)
    at eval (element.ts:200)
    at HTMLInputElement.eval (dom_renderer.ts:52)

Lets look at the code which is causing this issue .

<form class="example-form">
  <mat-form-field class="example-full-width">
    <input type="text" placeholder="Pick one" aria-label="Number" 
    matInput [formControl]="myControl" [matAutocomplete]="matAutocomplete">
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let option of options" [value]="option">
        {{option}}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>


You can see we have a mat-autocomplete  with a template reference variable #auto and the value as matAutocomplete. Also notice that property binding [matAutocomplete] is having value as mat

Now the error is due to we are using the value of the template reference variable instead of the reference .

Lets correct the code .

<form class="example-form">
  <mat-form-field class="example-full-width">
    <input type="text" placeholder="Pick one" aria-label="Number" 
    matInput [formControl]="myControl" [matAutocomplete]="auto">
    <mat-autocomplete #auto="matAutocomplete">
      <mat-option *ngFor="let option of options" [value]="option">
        {{option}}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>

Hope this fixes the issue you are facing .

No comments:

Post a Comment

ec2-user@ec2 Permission denied