ngStyle在angular2中不起作用!important

MD.*_*lam 2 angular

在angular2模板中,如果我写:

[ngStyle]="{'background-color': 'red'}"
Run Code Online (Sandbox Code Playgroud)

它按预期工作.但如果我写:

[ngStyle]="{'background-color': 'red !important'}"
Run Code Online (Sandbox Code Playgroud)

它不工作(也没有显示任何错误)

MD.*_*lam 6

由于angular2文档仍然不够好,我认为将解决方案作为答案发布可能会有所帮助(可能对某人有帮助).

根据angularjs(1.x)git仓库问题

您无法在Chrome或FF(也可能是其他人)的DOM样式属性中使用!important指令

因此,不要在[ngStyle]中使用!important,而是使用以下方法使其工作:

[attr.style]="'background-color:red !important'"
Run Code Online (Sandbox Code Playgroud)

它按预期工作.