I am in need of help with styling a component using CSS styles specified by an object of selectors to CSS properties. Check out my sandbox here: https://codesandbox.io/s/happy-goldberg-4740z
Here are the styles to be applied from the parent:
const styles = {
a: [
['color', 'red']
],
b: [
['color', 'blue']
]
};
Now, let's take a look at the component that needs to be styled dynamically:
@Component({
selector: 'test',
template: `
<div>
<span class="a">I am A</span>
<span class="b">I am B</span>
</div>
`
})
export class Test implements OnInit {
@Input() stylesToApply: { [key: string]: string[][] };
constructor(private _renderer: Renderer2, private _element: ElementRef) {}
ngOnInit() {
let styleText = '';
Object.entries(this.stylesToApply).forEach(([key, value]) => {
const selector = `:host ${ key }`;
let propStr = '';
for (let i = 0; i < value.length; i++) {
propStr += `${ value[i][0] }: ${ value[i][1] };\n`;
}
styleText += `${ selector} { ${ propStr } }\n`;
});
const styleElement = this._renderer.createElement('style');
this._renderer.appendChild(styleElement, this._renderer.createText(styleText));
this._renderer.appendChild(this._elementRef.nativeElement, styleElement);
}
}
Although the result should be a <style>
element injected into Test
as shown below, I'm facing issues where the styles are not being properly applied:
<style>
:host a { color: red; }
:host b { color: blue; }
</style>