Angular2 Material2如何设置样式元素

时间:2016-06-06 15:39:46

标签: angular angular-material2

我很好奇为什么我的某些scss无法正确使用angular-material2元素。我使用node-sass来编译我的scss,它似乎没有正确地影响css文件。例如,我正在使用具有以下内容的material2演示应用程序:

.demo-sidenav-layout {
   md-sidenav {
        background-color: $left_nav;
        padding: 10px;
   }
}

(我添加了背景色)。这是设置元素样式的正确方法,还是应该只使用类。当我添加一个具有所需背景颜色的类时,它被默认元素样式覆盖。

1 个答案:

答案 0 :(得分:1)

Material2使用核心元素的主题库。您可以使用带有Sass的mixins修改样式,或者为您的应用程序定义特定主题。使用方法是:

首先,使用官方文档创建主题:

其次,为所选组件创建一个mixin:

完成此操作的方法很简单。您必须创建一个新组件,例如

ng g c components/my_component_styleded

这创建了4个文件:

  • my_component_styleded.component.html
  • my_component_styleded.component.html.scss
  • my_component_styleded.component.spec.ts
  • my_component_styleded.component.html.ts

在* .scss中包含组件的一般样式(结构样式),在* .html文件中包含yout组件的结构HTML。 例如:

<div>
 <button md-raised-button routerLink="/stock">STOCK OF PRODUCTS</button>
</div>

现在,在目录中创建了一个名为“my_component_styleded.component.html.scss-theme.scss”的新文件,并使用以下代码使用mixin来个性化按钮元素:

@import '~@angular/material/theming';
@mixin my_component_styleded-theme($theme) {
    $primary: map-get($theme, primary);
    $accent: map-get($theme, accent);

    div {
    button {
        color: $accent;
        &:hover, &:focus {
            color: $primary;
            border-left: 5px solid mat-color($accent);
            }
        }
    }
}

你可以用Sass和其他东西声明其他变量。

最后,您必须在App的主要style.scss中添加此mixin:

- style.scss -

@import '~@angular/material/theming';
@include mat-core();

// Custom component themes:
@import 'app/components/my_component_styleded/my_component_styleded.component.scss-theme';
@mixin custom_component-theme($asis-light-theme) {
    @include my_component_styleded-theme($asis-light-theme);
}

// Light Theme
@include angular-material-theme($asis-light-theme);
@include custom-component-theme($asis-light-theme);