How to add class on mat-menu overlay in Angular 5?

14,537

Solution 1

Add backdropClass to the mat-menu, and then add style in the global style file. That cdk-overlay-pane is the one you want to style for, I think. For example:

<mat-menu #subMenu="matMenu" backdropClass="sg-vertical-sub-menu">
</mat-menu>

.sg-vertical-sub-menu+* .cdk-overlay-pane {
    margin-top: 12px;
}

Solution 2

I had the same issue, this is what I've done to position the menu below my toolbar.

::ng-deep .cdk-overlay-pane {
  top: 48px!important;
}

Solution 3

@Tom Jiang did it works fine, but adding css in styles.css might be a bit inconvenient and difficult to find code.

The better way: If you want to change your component only without affecting other components, you should add a class to the menu.

<mat-menu #infoMenu="matMenu" class="customize"></mat-menu>

Then style your menu with ::ng-deep.

::ng-deep .customize {
  background: red;
}

voila!! your customization will not affect other components.

Share:
14,537
Jimit
Author by

Jimit

Zend Certified Engineer (ZCE)

Updated on June 11, 2022

Comments

  • Jimit
    Jimit about 2 years

    I checked mat-menu API (https://material.angular.io/components/menu/api#MatMenu) but I couldn't find how to add a class on mat-menu cdk overlay.

    I want to add a class on cdk overlay which contains mat-menu template. Can anyone help on the same?

    I want to add class on parent cdk overlay because in responsive menu is not opening correctly. Check this below image.

    enter image description here

  • Martin Choraine
    Martin Choraine almost 6 years
    The response is great but it affects all ckd-overlay-pane. Adding a backdropClass is preferable
  • Cammy
    Cammy over 5 years
    Thanks for this! Some deep-digging in the docs is required to find this.
  • Cammy
    Cammy over 5 years
    Also heads up that ::ng-deep is going deprecated.
  • Winnemucca
    Winnemucca almost 5 years
    missing something on the element + element Selector. I am not able to get this to work. .sg-vertical-sub-menu+* .cdk-overlay-pane
  • Awais
    Awais over 4 years
    This add class to cdk-overlay-backdrop but i need to add it on one level above that is cdk-overlay-container
  • Bogdan
    Bogdan over 4 years
    cdk-overlay is not included in mat-menu element, it's inserted in body, so your solution is not correct.
  • Grochni
    Grochni over 3 years
    This won't work if hasBackdrop is set to false. Any ideas for that case?
  • Raphaël Balet
    Raphaël Balet almost 3 years
    Also, we shouldn't use ::ng-deep anymore, since it's deprecated