[Fixed] How to display mat-menu after entering 3 characters in input field?

Issue

I’m implement this input field so that when I enter 3 characters I want to display mat-menu as a value of mat-option but for some reason the mat-menu never gets display. Can anyone point me in the right direction? thanks a lot in advance!

Here’s LIVE DEMO

<mat-autocomplete #auto="matAutocomplete">
    <mat-option *ngIf="isSpinnerLoading">

  <div *ngIf="!menuContent">Loading...</div>
  <div *ngIf="menuContent">
    show menu

    <mat-menu #menu="matMenu" class="menu-select">
            <div (click)="$event.stopPropagation()">
                <div *ngFor="let item of myList">
                    <mat-checkbox
                        class="mat-menu-item">
                        {{item}}
                    </mat-checkbox>
                </div>
            </div>
        </mat-menu>
  </div>
    </mat-option>
</mat-autocomplete>

This is what I’m trying to accomplish:

enter image description here

Solution

Problem

The problem that you are facing is that the mat-menu openMenu()function is not triggered when your content opens

Solution

We will need a way to trigger the menu to open
Below is an approach that I have used

Add the below markup in your html

<span #menuTrigger="matMenuTrigger"  [matMenuTriggerFor]="menu">show menu</span>

In your TS file add below @ViewChild property to hold the matMenuTrigger

  @ViewChild("menuTrigger", { static: false }) set menuTrigger(
    content: MatMenuTrigger
  ) {
    if (content) {
      this.contentPlaceholder = content;
    }
  }

Finally amend your onKeyUp() function

  onKeyUp() {
    if (this.currentText.length >= 3) {
      console.log("testing");
      this.isSpinnerLoading = true;
      this.menuContent = false;
      setTimeout(() => {
        this.menuContent = true;
      }, 2000);
      setTimeout(() => {
        this.contentPlaceholder.openMenu();
      }, 2001);
    } else {
      this.isSpinnerLoading = false;
    }
  }

Note that we are triggering openMenu() after the this.menuContent() becomes true

See Demo

Leave a Reply

(*) Required, Your email will not be published