Search code examples
angularangular-materialangular-material-7

adding a class using ng-class to a mat-menu


I'm trying to add a custom class to a mat-menu in my app, the value is visible to the component which includes this piece of HTMl and it evaluates to true on a DOM element sibling, but it doesn't really seem to apply to it when I inspect the resulting HTML, also the mat-menu container is added as a direct child to the body HTML element although the containing component is encapsulated into multiple angular components.

my HTML is as follows

        <mat-menu class="more-menu" [ngClass]="{ dutch: languageFlag === 'nl' }" #cardOptions="matMenu" xPosition="before" [overlapTrigger]="false">
          <button mat-menu-item>
            Button 1
          </button>
          <button mat-menu-item>
            Button 2
          </button>
        </mat-menu>

I can find the 'dutch' class added to other elements but not to the mat-menu


Solution

  • Use class which is input property which takes classes set on the host mat-menu, element and applies them on the menu template that displays in the overlay container.

    @Input('class') panelClass: string

    <mat-menu class="customClass" #menu="matMenu">
      <button mat-menu-item>Item 1</button>
      <button mat-menu-item>Item 2</button>
    </mat-menu>
    

    Example