shaelex
shaelex

Reputation: 261

Angular matMenu with the width of trigger

Is there any chance to specify a width of matMenu depending on the button which is triggering that menu? I want matMenu to be as width as the trigger is. Trigger is in flex so the width is not const.

<button mat-button [matMenuTriggerFor]="menu">{{currentFactory?.name}}</button>
   <mat-menu #menu="matMenu">
        <button mat-menu-item *ngFor="let factory of factories; let i = index"
              (click)="changeCurrentFactory(i)">{{factory?.name}}</button>
   </mat-menu>

Upvotes: 5

Views: 1409

Answers (1)

Mike_G
Mike_G

Reputation: 16512

I just got done doing this. In my case I have a container around the button. You can reference the html element you want to get the width for, then use ngStyle to set the width of the menu items.

<div #elementIWantWidthOf>
 <button mat-button [matMenuTriggerFor]="menu">{{currentFactory?.name}}</button>
<div>
   <mat-menu #menu="matMenu">
    <button mat-menu-item
            [ngStyle]="{'width':getWidth(elementIWantWidthOf)}
           *ngFor="let factory of factories; let i = index"
          (click)="changeCurrentFactory(i)">{{factory?.name}}</button>
   <mat-menu>

then in your component just have a method of getWidth:

 getWidth(element: HTMLElement) {

    return `${element.clientWidth}px`;
 }

Upvotes: 1

Related Questions