1
votes

I would like to apply a dynamic style to the content of mat-menu. I know that I can use panelClass to assign a class, but my class is dynamic.

Angular has a [ngStyle] or just [style.attribute] binding for such cases, but that does not work on the mat-menu (or other overlays), it only works on directly rendered elements.

I am looking for something like panelStyle which would allow me to set the styles dynamically directly on the panel which holds the mat-menu.

Here is a code example, where panelClass allows me to set some css, but only static one and ngStyle is useless.

<mat-menu [ngStyle]="{'background-color': colorVariable }" panelClass="some-static-class-works">

What I am looking for:

<mat-menu [panelStyle]="{'background-color': colorVariable }">
1
I've responded to another similar request with a simple example: please check: stackoverflow.com/questions/55111607/…. the same principle can be applied to suit your needs.jcuypers
I see your point, but in your example you are just using static classes (eg .red, .green) that all have to be defined beforehand. My situation is a bit more complex and if I take your approach I will have to create tens of static classes instead of creating them dynamically.hoonzis
But you can make it as dynamic as you want. just bind it... you dont need to preconfigure:)jcuypers
The answer that G.Tranter provided is a fully dynamic solution. Your idea is nice and might be used for other situations where introducing inner div is not possible. But it requires to create as many css class as dynamic options that one might need. Thanks - I am sure it will be used in other scenarioshoonzis

1 Answers

6
votes

You can wrap your menu content in a single DIV and apply style dynamically to that. With background-color, to get it to fill the entire panel you need to adjust margins and padding. For example:

<mat-menu>
  <div [ngStyle]="{'background-color': colorVariable }" class="menu-panel">
    <button mat-menu-item>Item 1</button>
    <button mat-menu-item>Item 2</button>
  </div>
</mat-menu>

.menu-panel {
  margin: -8px 0; 
  padding: 8px 0;
}