Home > OS >  Angular dynamically change class style content
Angular dynamically change class style content

Time:10-06

I know the name of the class i want to change the content of dynamically. So i don't need to get any element by its id or so. I just want to change the content of the class at any time.

I can't add class or ngclass in the html because this html is not generated in my own code

So for example, say the class is like so:

.garden {
color = white;
}

I just want to change the content to

.garden {
color = red;
}

and have it applied to all HTML elements having this class style

How may i do that ? I don't find a method like document.getCssByName("garden")

Thank you

CodePudding user response:

If you have the class name you can do something like this as a workaround:

const cssClass = '.garden {color = red !important;}';
style = document.createElement('style');
document.head.appendChild(style);
style.type = 'text/css';
style.id = 'myTempStyle';
if (style.styleSheet){
  style.styleSheet.cssText = css;
} else {
  style.appendChild(document.createTextNode(css));
}

And for deletion:

documet.getElementById('myTempStyle').remove();

CodePudding user response:

Maybe is this a solution:

ngAfterViewInit() {
    document.querySelector('.garden' as HTMLElement).style.color = 'red';
}
  • Related