我有一个带有样式表的组件,可以像这样正确加载:
@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>
如何有条件地加载这样的附加样式表呢?我不知道还有什么可以尝试。
答案 0 :(得分: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');
}
}
答案 1 :(得分:0)
我发现它的唯一方法就是这样做:
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();
}