【问题标题】:Angular: How to change material theme and retain some custom css?Angular:如何更改材质主题并保留一些自定义 CSS?
【发布时间】:2020-01-02 00:07:42
【问题描述】:

我希望用户能够登录我们的应用,将材料主题更改为他们的公司颜色,同时在这些材料组件上保留一些自定义 CSS。

我正在处理一个项目,我们希望在登录时根据用户/他们的公司更改材料主题。
我的问题是,当应用程序加载时,它会加载全局样式和材质主题,一切看起来都很好。但是在登录时——当我更改材质主题时——新主题似乎覆盖了我们添加到材质组件中的一些自定义 CSS(例如 mat-tables 中 mat-rows 的背景颜色)。我不知道如何保留我的自定义 CSS 或保留材质主题以覆盖它。现在我正在处理一个被覆盖的类,但一旦我找到解决方案,就会扩展到其他所有内容。
我试过了:
- 将自定义类拉入延迟加载的样式表,在主题更改后立即加载。
- 将 ::ng-deep 添加到 styles.scss 中的类。
- 将 ::ng-deep 添加到延迟加载样式表中的类。

styles.scss

.matRowDefault {
    margin-bottom: .8rem;
    background: white;
    border-radius: 5px;
    height: 50px;
    border-left: 7px solid gray;
}

主题.scss

$dpa-primary: mat-palette($mat-deep-purple);
$dpa-accent: mat-palette($mat-amber);
$dpa-warn: mat-palette($mat-basicRed);

$dpa-theme: mat-light-theme($dpa-primary, $dpa-accent, $dpa-warn);
.dpa-theme {
    @include angular-material-theme($dpa-theme);
}

component.html

<mat-row class="matRowDefault" (mouseenter)="selectRow(row)" (mouseleave)='selectedRow = ""'>
</mat-row>

app.component.ts

  setTheme(theme) {
    if (theme.toLowerCase() != "default-theme") {
      this.overlayContainer.getContainerElement().classList.add(theme);
      this.componentCssClass = theme;

      var customUrl = '../assets/customColors2.css';
      this._srv.loadExternalStyles(customUrl);
    }
  }

beta.service.ts

  loadExternalStyles(styleUrl: string) {
    return new Promise((resolve, reject) => {
      const styleElement = document.createElement('link');
      styleElement.rel = 'stylesheet';
      styleElement.href = styleUrl;
      styleElement.onload = resolve;
      document.head.appendChild(styleElement);
    });
  }

使用上面的单一样式类,组件样式覆盖边框(这很好),新主题覆盖背景到背景:继承使行与表格颜色相同(不是我想要的),并且然后我可以看到styles.scss 中的其余样式仍然存在。
所以一切正常,我只需要一种巧妙的方法来防止主题覆盖我已经拥有的任何自定义 CSS。

【问题讨论】:

    标签: css angular sass


    【解决方案1】:

    我认为您正在寻找的解决方案是 Angular 的 ViewEncapsulation 属性。有 4 个选项:Emulated、Native、None 和 ShadowDom。

    请看这里:https://angular.io/api/core/ViewEncapsulationhttps://blog.thoughtram.io/angular/2015/06/29/shadow-dom-strategies-in-angular2.html

    我认为您正在寻找的解决方法是在您想要使用自定义 CSS 的每个组件中使用 ViewEncapsulation.Native。本质上,它将允许您不将全局样式应用于该特定组件。

    组件.ts

    @Component({
      encapsulation: ViewEncapsulation.Native,
      selector: 'app-component',
      templateUrl: './component.html',
      styleUrls: ['./component.scss']
    })
    

    【讨论】:

      猜你喜欢
      • 2019-06-11
      • 2018-01-02
      • 2019-07-06
      • 2018-10-08
      • 1970-01-01
      • 2020-07-10
      • 1970-01-01
      • 2020-08-06
      • 2021-02-27
      相关资源
      最近更新 更多