S. *_*son 8 css string interpolation styles angular
@Component({
selector: 'app-style',
template: `
<style>
.test {
color: {{ textColor }}
}
</style>
`
})
export class StyleComponent {
textColor = "red";
}
Run Code Online (Sandbox Code Playgroud)
这似乎不起作用,我需要我的样式是动态的,并在一些特定的CSS类.还有其他方法可以做到这一点吗?
当组件被渲染时,style 标签将移动到页面的 head 元素,并且该元素内的任何 angular 语法都将被忽略。
我发现的唯一方法是动态创建样式元素并提供所需的样式。
app.component.ts
textColor = 'red';
constructor(private el: ElementRef) {
}
ngOnInit() {
let style: string = `
.test {color :${this.textColor}; }
`;
this.createStyle(style);
}
createStyle(style: string): void {
const styleElement = document.createElement('style');
styleElement.appendChild(document.createTextNode(style));
this.el.nativeElement.appendChild(styleElement);
}
Run Code Online (Sandbox Code Playgroud)
应用模板.html
<span class="test">test</span>
Run Code Online (Sandbox Code Playgroud)
您可以像这样使用 ngStyle 指令;
@Component({
selector: 'app-style',
template: `
<ul>
<li [ngStyle]="{color: textColor}">List Item</li>
</ul>
`
})
export class StyleComponent {
textColor = "red";
}
Run Code Online (Sandbox Code Playgroud)
您可以通过[style.color]在样式表中指定定义的类来访问颜色样式[class]:
<div [style.color]="color">Style Test</div>
<div [class]="className">Class Test</div>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4951 次 |
| 最近记录: |