@Component({
selector: 'app-style',
template: `
<style>
.test {
color: {{ textColor }}
}
</style>
`
})
export class StyleComponent {
textColor = "red";
}
这似乎不起作用,我需要我的样式是动态的并且在某些特定的 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);
}
app.template.html
<span class="test">test</span>
关于css - 如何在 Angular 组件的样式标签中使用字符串插值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50189526/