我有两个使用mat菜单的组件。我只想为一个组件中的一个菜单添加一些额外的样式。我已经在组件css中使用了此css
::ng-deep.mat-menu-panel
{
position: fixed !important;
right : 2%;
}
现在的问题是css也正在应用于其他组件mat菜单。 我该如何解决?
答案 0 :(得分:2)
将面板样式添加到全局样式表中:
selector
在面板菜单中添加面板样式:
.fixed-menu-panel
{
position: fixed !important;
right : 2%;
}
StackBlitz:https://stackblitz.com/edit/angular-9bheaf?file=index.html
答案 1 :(得分:1)
挑战在于菜单是在附加到父文档的覆盖容器中呈现的,而不是在按钮本身上呈现的。要记住这一点,您将需要考虑如何获取对该{{1}的引用}并向其添加一个类,以使其在打开菜单时具有唯一性。
例如,您可以执行以下操作来完成此操作。
创建一个组件方法,该方法将接收mat-menu-panel
作为参数。它将使用templateRef
获取mat-menu-panel
并将一个类附加到Renderer2
styled
然后在您的视图中,在菜单打开时,使用 styleMenu(el) {
const menuPanel = this.ren.parentNode(this.ren.parentNode(el.items.first['_elementRef'].nativeElement));
this.ren.addClass(menuPanel, 'styled')
}
事件发射器调用(menuOpened)
方法,并将styleMenu
templateRef作为参数传递。
#styledMenu
然后您的CSS将如下所示
<button mat-button [matMenuTriggerFor]="styledMenu" (menuOpened)="styleMenu(styledMenu)">styled</button>
<mat-menu #styledMenu="matMenu">
这是一种方法,您也可以将所有这些滚动到::ng-deep .mat-menu-panel.styled
{
position: fixed !important;
right : 2%;
}
中,然后在需要的地方应用指令directive
。
Stackblitz
https://stackblitz.com/edit/angular-5nixtl?embed=1&file=app/menu-overview-example.ts