How to change property values of an already existing css class in Angular2+ controller?

Viewed 21

I have a css class '.users' in my syles.css file and this class has a propery of color. Now I want to change the color propery value of users class base on some condition in my controller (for example in ngOnInt()) dynamically? please consider that I do not want to do anything in template, so only typescript solutions are accepted!

1 Answers

This is not a good approach to handle the styling this way. We need more declarative approach rather than coding imperatively.

Just for the sake of doing this approach which I highly un-recommend:

In styles.css:

--users-text-color: black;

.users {
  color: var(--users-text-color: black);
}

And in component.ts

constructor(private rendrer: Renderer2, private document: Document) {}

onInit(): void {
  this.renderer.setProperty(this.document, '--users-text-color', 'white');
}

THE PROPER WAY: The proper way would be to override styles like this

In styles.css:

.users {
  color: black;
}

And in component.scss

// Component level over-ride
.users {
   color: white;
}
Related