md-menu 覆盖 Angular 中的默认最大宽度 2

md-menu override default max-width in Angular 2

我正在使用 Angular 2 , Angular Material 并且我愿意在 md-menu 中显示更多数据,因此,我需要设置 md- 的最大宽度菜单设置为更高的值。它的默认值为 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>   

在 CSS 文件中,我这样做:

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

.notification-row{
    width: 424px;
}

在控制台中,我可以识别设置默认值的 class : max-width:280px; ,当我在我的控制台中编辑它时,它工作得很好,但即使我尝试覆盖它在我的 CSS 代码中,我无法做到这一点。我也试过这个:

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

还有这个:

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

如何覆盖此默认值?

在您的组件上将 View Encapsulation 设置为 None:

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

然后在您的组件中 css 您可以完全按照您的尝试进行操作:

.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.

在某些情况下 .mat-menu-panel 的包装可以是 .cdk-overlay-pane,在这种情况下 css 应该是这样的。

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

由于 css 特异性规则,需要 2 类 特异性才能覆盖默认值。

我遇到了同样的疯狂问题...我是如何解决的:

::ng-deep .cdk-overlay-pane .mat-menu-panel {
  max-width: 436px;
}

在组件 SASS 文件中

参见:Angular Component Styles - View Encapsulation

并通过 @gaiki https://github.com/angular/material2/issues/4462

发表评论