【问题标题】:Angular 2 - How do I conditionally add styles to my component?Angular 2 - 如何有条件地向我的组件添加样式?
【发布时间】:2017-07-18 17:31:43
【问题描述】:

我有一个组件,其样式表可以像这样正确加载:

@Component({
  selector: 'open-account',
  styleUrls: ['open-account.component.scss'],
  templateUrl: './open-account.component.html',
})

如果字符串widget=true 出现在url 中但无论如何都无法工作,我想有条件地加载另一个样式表。我试过了:

var stylesArr = ['open-account.component.scss'];
if (window.location.href.indexOf('widget=true') > -1) stylesArr.push('open-account-widget-styles.component.scss');

@Component({
  selector: 'open-account',
  styleUrls: stylesArr,
  templateUrl: './open-account.component.html',
})

var stylesArr = ['./open-account.component.scss'];
if (window.location.href.indexOf('widget=true') > -1) stylesArr.push('./open-account-widget-styles.component.scss');

@Component({
  selector: 'open-account',
  styleUrls: stylesArr,
  templateUrl: './open-account.component.html',
})

@Component({
  selector: 'open-account',
  styleUrls: ['open-account.component.scss', 'open-account-widget-styles.component.scss'].filter(elem => {
    if (elem === 'open-account.component.scss') return true;
    if (elem === 'open-account-widget-styles.component.scss' && window.location.href.indexOf('widget=true') > -1) return true;
  }),
  templateUrl: './open-account.component.html',
})

在我的 html 顶部:

<style type="text/css" *ngIf="false">
(the 'false' would be a variable, but putting in false doesnt even stop the style from loading)
...
</style>

如何有条件地加载这样的附加样式表?我不确定还能尝试什么。

【问题讨论】:

  • 如果您将组件加载为小部件,您想使用不同的 css 吗?你是如何构建你的应用程序的?你在使用 AOT 吗?
  • @SanderElias 确切地说,如果我将组件作为小部件加载并且我正在 AOT 中构建,我想加载一个额外的 sytlesheet
  • @SanderElias 也是,在我们将构建切换到 AOT 之前,这些方法中的许多曾经可以工作,现在它们都不起作用
  • 不能使用 AOT 的原因是执行顺序不同。您用于“选择”样式表的代码是在编译时调用的,而不是在运行时调用的。您可以在编译前更改样式数组,但不能在编译后更改。
  • 您需要在运行时加载样式表,还是可以将它们存储为应用代码的一部分?

标签: angular typescript angular2-styleguide


【解决方案1】:
 import { Component, Inject } from '@angular/core';
 import { DOCUMENT } from '@angular/platform-browser';

 @Component({
 })

 export class SomeComponent {

    constructor (@Inject(DOCUMENT) private document) { }

        LightTheme() {
            this.document.getElementById('theme').setAttribute('href', 'light-theme.css');


        DarkTheme() {
            this.document.getElementById('theme').setAttribute('href', 'dark-theme.css');
    }
}

【讨论】:

  • 您通过 id 获得的 theme 元素是什么?
【解决方案2】:

我发现它起作用的唯一方法是这样做:

addStyleSheet() {
  var headID = document.getElementsByTagName('head')[0];
  var link = document.createElement('link');
  link.type = 'text/css';
  link.rel = 'stylesheet';
  link.id = 'widget_styles';
  headID.appendChild(link);

  link.href = './app/open-account/open-account-widget-styles.component.css';
}

ngOnInit() {
  this.addStyleSheet();
}

【讨论】:

    猜你喜欢
    • 2017-05-22
    • 2023-03-30
    • 2018-06-29
    • 2017-09-11
    • 2018-05-15
    • 2019-10-11
    • 2016-08-01
    • 1970-01-01
    相关资源
    最近更新 更多