3

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

@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>

我该怎么做才能有条件地加载这样的附加样式表?我不知道还能尝试什么。

4

2 回答 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();
}
于 2017-02-28T19:17:16.140 回答
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');
    }
}
于 2017-02-28T06:28:58.780 回答