Angular 2 - 如何在我的组件中有条件地添加样式?

4

我有一个带有样式表的组件,正确加载方式如下:

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

如果URL中存在字符串widget=true,我希望能有条件地加载另一个样式表,但是我找不到任何方法让它工作。我尝试过:

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吗? - Sander Elias
@SanderElias 没错,如果我正在将组件作为小部件加载并且正在进行AOT构建,则希望加载其他样式表。 - georgej
@SanderElias 此外,许多这些方法在我们将构建切换到AOT之前曾经有效,但现在它们都不起作用了。 - georgej
无法与AOT一起使用的原因是执行顺序不同。用于“选择”样式表的代码在编译时被调用,而不再是运行时。您可以在编译之前更改样式数组,但不能在之后更改。 - Sander Elias
你需要在运行时加载样式表,还是将它们作为应用程序代码的一部分存储就可以了? - Sander Elias
@SanderElias 需要在运行时加载它们,因为这取决于输入此页面的 URL 是否符合条件。 - georgej
2个回答

1
我找到的唯一方法是这样做:

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();
}

0
 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”元素? - georgej
@georgej 的主题是元素 ID。 - Yoav Schniederman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接