@Component({
selector: 'app-style',
template: `
<style>
.test {
color: {{ textColor }}
}
</style>
`
})
export class StyleComponent {
textColor = "red";
}
This doesn't seem to be working and I need my styles to be dynamic and in some specific CSS class. Is there some other way I could do this?
When the component is renderd the style tag will move to head element of the page and any angular syntax inside this element will be ignored.
the only way I have found is to create the style element dynamic and provide the desire style.
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>
stackblitz demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With