Change Angular 2/4 Material default styles for “md

2019-08-20 12:20发布

I'm trying to change default Angular Material styles of md-menu. The problem is the Angular Material generates elements dynamically and I can't get access to them from my HTML.

Here is my DOM:

enter image description here

And here is my component HTML (md-menu generates that DOM):

<md-toolbar color="primary">
  <h1>Logo</h1>
  <span class="spacer"></span>
  <img src="../../../images/avatar-default.png" class="avatar" [mdMenuTriggerFor]="userMenu" />

  <md-menu #userMenu="mdMenu">
    <button md-menu-item>{{username}}</button>
    <button md-menu-item>Log Out</button>
  </md-menu>
</md-toolbar>

I know that I can get access to that div (selected on the picture) from global styles using .mat-menu-content {...}, but it will affect other elements with such classes. And I'm unable to set styles to this div from component CSS, because the element is outside component scope. So I'm trying to find the way to change styles of this element from component CSS and without affecting other elements with such style.

If there is a way to implement it, please, let me know.

2条回答
戒情不戒烟
2楼-- · 2019-08-20 12:42

Described in the picture below,Maybe this doc would help enter image description here

查看更多
在下西门庆
3楼-- · 2019-08-20 12:54

Check if using /deep/ is an option for you.

Component styles normally apply only to the HTML in the component's own template.

Use the /deep/ selector to force a style down through the child component tree into all the child component views. The /deep/ selector works to any depth of nested components, and it applies to both the view children and content children of the component.

Doc

component.css:

/deep/ .mat-menu-content {
    background: skyblue !important;
    border-top: solid 1px black;
    border-bottom: solid 1px black;
}

/deep/ .mat-menu-item {
    padding: 0 0 0 0 !important;
}

demo

查看更多
登录 后发表回答