Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use mat-input while mat-menu is opened in Material2

When <mat-menu> is used on <mat-form-field> it takes the focus from the input. I want the user to be able to use the input while the menu is opened.

Is this possible?

<mat-form-field appearance="outline" [matMenuTriggerFor]="appMenu">
  <mat-label>Label color</mat-label>
  <div class="color-container">
    <div class="color-dot" [style.backgroundColor]="label.color"></div>
  </div>
  <input #input matInput class="pl-2" [(ngModel)]="label.color">
</mat-form-field>


<mat-menu #appMenu="matMenu" yPosition="below" [overlapTrigger]="false">
  <mat-grid-list cols="8" rowHeight="30px">
    <mat-grid-tile *ngFor="let color of colors">
      <div mat-menu-item class="menu-item">
        <div class="color-dot" [style.backgroundColor]="color" 
                               (click)="label.color = color"></div>
      </div>
    </mat-grid-tile>
  </mat-grid-list>
</mat-menu>

stackblitz example

like image 820
Murhaf Sousli Avatar asked Dec 18 '22 21:12

Murhaf Sousli


2 Answers

You can easily achieve this by adding

<mat-menu #myMenu="matMenu">
    <form (click)="stopPropagation($event)">
        <!-- Your content and inputs -->
    </form>
</mat-menu>

And in your component

stopPropagation(event){
    event.stopPropagation();
}

This will prevent the event propagation, so the button that opens the menu won't receive the "toggle" trigger.

EDIT: As Jakub said in the comments, you can also skip the function creation and immediately call the stopPropagation method from the template with

  <form (click)="$event.stopPropagation()">
like image 153
Luca De Nardi Avatar answered Dec 28 '22 10:12

Luca De Nardi


As far as I understood you want your inputs outside the mat-menu, in lower level, while having the mat menu open with different color options as reference. If that's not the case, you should put the mat-form-field tag inside mat-menu tag, as pointed above. Only thing is I don't understand why then you have to prevent the mat-menu from closing on focusing on the inputs, 'cause that has never happens to me, only with tab key which closes the menu if you have inputs inside it, on that case you have to catch the keydown event and prevent it, with the problem of preventing also ESC key... But If what you want is the menu to be open and be able to write on your inputs on a lower level at the same time, what you have to do is to disable backdrop for your mat-menu. That you can make it on the html like this:

<mat-menu #myMenu="matMenu" [hasBackdrop]="false"></mat-menu>
like image 43
Chema Avatar answered Dec 28 '22 10:12

Chema