对于给定的js变量,其中包含样式信息:
menuBgColor = "red";
在AngularJS中,我能够使用动态嵌入式样式:
<div>
<style>
.menuElement{
background-color:{{menuBgColor}}
}
</style>
<div class="menuElement">...</div>
</div>
在Angular2 +我不能使用与上面相同。当在浏览器变量中呈现视图时,不会填充menuBgColor
,并且元素将呈现为已编码。
像这样 -
<body>
...other markup...
<div><style>.menuElement{background-color:{{menuBgColor}}}</style>
...markup...
</body>
我想知道在角度2+中为视图添加动态样式的其他方法是什么?
任何帮助是极大的赞赏。
你可以试试这个:
<div [style.background-color]="yourVar"></div>
在这种情况下,绑定应该工作
没有像Angular Material那样构建巨大的结构,没有很好的方法可以做到这一点。但是,如果您的主题系统不是那么复杂,我只需要动态渲染<link>
标签到您的主题,如下所示:
import { Component } from '@angular/core'
import { DomSanitizer } from '@angular/platform-browser'
@Component({
selector: 'my-app',
template: `
<link rel="stylesheet" [href]="getThemeUrl()">
<div class="main">
{{'themes/css/'+ theme +'.css' }}
<select [(ngModel)]="theme" (change)="onThemeChanged(theme)">
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="yellow">Yellow</option>
</select>
</div>
`
})
export class AppComponent {
theme = 'red';
constructor(public sanitizer: DomSanitizer){}
getThemeUrl(){
return this.sanitizer
.bypassSecurityTrustResourceUrl('themes/' + this.theme + '.css');
}
}