Angular 2-如何有条件地向我的组件添加样式? [英] Angular 2 - How do I conditionally add styles to my component?
本文介绍了Angular 2-如何有条件地向我的组件添加样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个样式表正确加载的组件,如下所示:
I have a component with a stylesheet that loads correctly like this:
@Component({
selector: 'open-account',
styleUrls: ['open-account.component.scss'],
templateUrl: './open-account.component.html',
})
如果字符串widget=true
存在于url中,但无论如何都无法工作,我想有条件地加载另一个样式表.我已经尝试过:
I want to conditionally load another stylesheet if the string widget=true
is present in the url but cannot get anyway to work. I have tried:
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顶部:
and in at the top of my 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>
如何有条件地加载这样的其他样式表?我不确定还可以尝试什么.
What can I do to conditionally load an additional stylesheet like this? Im not sure what else to try.
推荐答案
我发现它起作用的唯一方法是执行以下操作:
The only way I found it works is to do this:
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();
}
这篇关于Angular 2-如何有条件地向我的组件添加样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文