Using Angular’s reactivity for dynamic CSS styling

View-manipulation with Angular’s reactivity

Made by Itchimonji

You can use the reactivity of Angular in class- or ngClass-attributes of HTML elements. With this combination you can change your stylings dynamically at runtime — which would be helpful for theme components.

First of all, you need a variable of the current theming in a controller. This variable is a good starting point for using reactivity.

>>> app.component.ts

public theme: string;

constructor() {
this.theme = 'light';
}

Secondly, you need to define the theming in the stylesheet with some rules. Here you can use CSS, SCSS, SASS or other preprocessors. For this example a light and a dark theme are only needed.

>>> app.component.css

div.dark {
background-color: black;
color: white;
}

div.light {
background-color: white;
color: black;
}

Reactivity in Angular’s HTML files are managed with double curled brackets, e.g. {{var}} .

Afterwards you need to attach the theming variable to a class- or ngClass-attribute. Now the view can consume the content of the variable and would be changed, if the variable changes.

>>> app.component.html<div class="section {{theme}}">
Here you can see the result of theming.
</div>

That’s all, now you can switch the theming of the div-section by choosing a dark and light mode, for example with an HTML select element.

>>> app.component.html<div class="{{theme}}">
<div>
Here you can see the result of theming.
</div>
<div>
<label for="theme">Choose a theme:</label>
<select name="theme" id="theme" [(ngModel)]="theme">
<option value="light">light</option>
<option value="dark">dark</option>
</select>
</div>
</div>

You bind the variable theme to the select element with the id=theme and the decorator [(ngModel)]. In the select element every option gets a value. So, by changing the selected value of the element, you change the value of the theme declaration. This is possible on the basis of [(ngModel)] — take a look at Angulars Docs about NgModel.

Now you can change the class of the div element at runtime dynamically.

Conclusion

This is one of thousands of other methods to combine your stylesheets and the controller with the reactivity of Angular. Maybe you know or find other ones. Try it out!

Thanks for reading and Happy Coding! :)

Code example on Github

Learn More

Written by

Fullstack Software Engineer | Trained Mathematical-Technical Software Developer | Employee at Energy2market

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store