【问题标题】:Where to apply the parent theme class when using :host-context(.theme_name) in Angular2?在Angular2中使用:host-context(.theme_name)时在哪里应用父主题类?
【发布时间】:2018-10-07 16:34:22
【问题描述】:

我正在构建一个主题 Angular2 应用程序。我有大量嵌套组件,我想通过更改一个父类来更改整个应用程序的主题。假设一个主题被称为“theme1”。当我将它应用于非常父 html-tag 时,所有嵌套的子组件将使用 :host-context 切换样式,如下所示:

:host-context(.theme1) .title-toc {
    font-family: "bookmania";
    font-weight: 700;
    font-size: 20pt;
    text-transform: uppercase;
    color: #a5a5a5;
}

但是,把这个 class="theme1" 放在哪里呢?当我将它放到<body> 时,它可以正常工作,因此代码本身可以正常工作,但我需要动态更改主题,因此它必须位于某个 Angular 组件内,而不是我可以使用[ngClass] 的地方。例如在 AppComponent 内部。但是当我将它放在 app.component 中时(例如 router-outlet 或任何其他应该包装我的整个应用程序的包装标签),它就不再起作用了。

我是否必须以某种方式使用 ::ng-deep 使其深入,否则可能有什么问题?

【问题讨论】:

  • 把它放在根组件上怎么样?您可以通过@HostBinding('attr.class') mainClass = 'theme1'; 进行设置
  • 这行得通!非常酷。谢谢!如果您将此添加为答案,我会接受。

标签: css angular themes


【解决方案1】:

:host-context() 查看应用于文档body的类。您可以在应用程序加载后使用 JavaScript 设置 body 的类,如下所示:

var myclass = "my-theme-name";
document.querySelector('body').classList.add(myclass);

这样您甚至可以从服务器加载主题名称,然后通过 JS 从任何 Angular2 组件将其应用到正文:

:host-context(.my-theme-name) .my-theme-specific-style

【讨论】:

    【解决方案2】:

    您可以像这样绑定到根组件元素的 class 属性:

    export class AppComponent implements OnInit {
    
      @HostBinding('attr.class') mainClass = 'theme1';
    
      changeTheme(theme) {
        this.mainClass = theme;
      }
    
    }
    

    【讨论】:

    • 顺便说一句,是否可以在保留主类已有的可能类的同时应用该类?似乎这种技术会覆盖当前的类(如使用 Bootstrap 时的 col-classes)
    • 我自己搞定了,看来我可以这样做:@HostBinding('attr.' + myClassNameInVariable) true;
    • 您还可以通过单独的布尔属性为每个主题绑定:@HostBinding('class.theme1') theme1 = true;
    • 哦,嗯,我不确定我的方法是否可行。以你的方式 - 如果类名“theme1”在一个变量中,我该怎么办?
    • 我认为你做不到。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-27
    • 2020-01-23
    • 2011-06-01
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    相关资源
    最近更新 更多