md-menu override default max-width in Angular 2

2019-04-07 07:18发布

I'm using Angular 2 , Angular Material and I am willing to display more data in a md-menu and, therefore, I need to set the max-width of the md-menu to a higher value. Its default value is of 280px.

    <img src="/assets/images/ic-notifications.png" [mdMenuTriggerFor]="appMenu"/> 
    <md-menu #appMenu="mdMenu"  [overlapTrigger]="false" yPosition="below" xPosition="before" class="notifications-dropdown">
        <button md-menu-item >
           <div class="row notification-row"> 
             <div>
               <span class="image-container"> Option 1 </span>
             </div>
           </div>
        </button>
    </md-menu>   

In CSS file, I do this:

.mat-menu-panel.notifications-dropdown {
    max-width:none;
    width: 100vw; 
    margin-left: -8px;
    margin-top: 24px;
    overflow: visible;
}

.notification-row{
    width: 424px;
}

In console, I can identify the class where the default value is set: max-width:280px; , and when I edit it in my console, it works perfectly, but even though I try to override it in my CSS code, I am not able to do that. I tried this, also:

.mat-menu-panel{
    max-width: 600px;
} 

And this:

.cdk-overlay-container .mat-menu-panel{
     max-width:600px;
    width: 100vw;
    margin-left: -8px;
    margin-top: 24px;
}

How can I override this default value?

2条回答
手持菜刀,她持情操
2楼-- · 2019-04-07 07:49

In some cases the wrapper over .mat-menu-panel can be .cdk-overlay-pane, in that case css should be something like this.

.cdk-overlay-pane. mat-menu-panel {
    max-width: your_custom_value
}

Due to the css specificity rules, 2 classes of specificity are required in order to override the defaults.

查看更多
欢心
3楼-- · 2019-04-07 07:55

Set the View Encapsulation to None on your component:

@Component({
    templateUrl: './my.component.html' ,
    styleUrls: ['./my.component.css'], 
    encapsulation: ViewEncapsulation.None,
})

Then in your component css you can do exactly what you tried:

.mat-menu-panel.notifications-dropdown {
    max-width:none;
    width: 100vw; 
    margin-left: -8px;
    margin-top: 24px;
    overflow: visible;
}

.notification-row{
    width: 424px;
}

View Encapsulation = None means that Angular does no view encapsulation. Angular adds the CSS to the global styles. The scoping rules, isolations, and protections discussed earlier don't apply. This is essentially the same as pasting the component's styles into the HTML.

查看更多
登录 后发表回答