Angular 角度2-样式在AOT构建中不起作用
如果url中存在参数Angular 角度2-样式在AOT构建中不起作用,angular,typescript,Angular,Typescript,如果url中存在参数widget=true,我将使用此函数向组件添加样式: addStyleSheet() { var headID = document.getElementsByTagName('head')[0]; var link = document.createElement('link'); link.type = 'text/css'; link.rel = 'stylesheet'; link.id = 'widget_styles'; headID.a
widget=true
,我将使用此函数向组件添加样式:
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';
}
它在实时构建(JIT)时工作得很好,但在提前构建(AOT)时不工作。这是为什么?我如何修复它?让我们用一个简单的例子来解释这一点。 想象这是你的路线:
{ path: '/widget', component: WidgetComponent }
您可以使用以下代码使用参数导航到该管线:
this.router.navigate(
['/widget'], { queryParams: { widget: 'true' } }
);
这将导致以下URL/widget;widget=true
注意:Angular使用分号来分隔参数,而不是问号
可以找到文档
在组件中,可以获得如下参数:
this.route
.queryParams
.subscribe(params => {
this.widget = params['widget'] === 'true';
});
此时,组件中有一个带有param的变量,现在可以使用条件样式
<div [ngClass]="{class_name: widget}">Lorum ipsum</div>
Lorum ipsum
这样,您就不会直接接触DOM,angular将处理一切。我不知道这个问题的确切答案,但我可以告诉您一件确定的事情:直接与DOM API交互通常被认为是不好的做法。如果需要动态地将样式应用于组件,请考虑在组件的根标记上使用属性指令。