This post takes you through using conditional styling in Angular with the ngClass directive and shows you many forms of application—super useful if you’re getting started in Angular.
Angular
Angular, Google’s JavaScript (TypeScript) framework for building web applications, mobile or desktop, has over 71,000 stars on GitHub. It’s maintained by the Angular team at Google and a host of community members and organizations.
Before You Start
To be able to follow through in this article’s demonstration you should have:
- An integrated development environment like VS Code
- Node version 11.0 installed on your machine
- Node Package Manager version 6.7 or higher (usually ships with Node installation)
- Angular CLI version 8.0 or higher
- The latest version of Angular
- Download this tutorial’s starter project here to follow through the demonstrations
- Unzip the project and initialize the node modules in your terminal with this command:
npm install
Other nice-to-haves include:
- A working knowledge of the Angular framework at a beginner level
In this post, you will learn to use the ngClass
directive for conditional styling of your Angular component elements.
Using CSS Classes in Angular
To style elements in your Angular component, you can simply use CSS in the component.css file and define all your styles. You can also use inline CSS just as you would use for any HTML page. The paragraph below has a class green:
<p class="green">All beginner courses are colored green</p>
The stylesheet would look something like this:
.green {
color: green;
}
Conditional Styling
The easiest way I can explain conditional styling is with mouse behavior—things like focus, hover, on click and active. The process of defining rules in your stylesheet based on a predefined condition (in this case, mouse behavior) is called conditional styling. The already mentioned examples are implemented natively in CSS using browser CSS pseudo-classes. What happens if you want to apply a style on an element based on some predefined conditions that are not natively reserved as CSS pseudo-classes?
ngClass Conditional Styling
The Angular team shipped the ngClass
directive to help developers add and remove CSS classes on HTML elements. There are three ways to use the ngClass
directive depending on the type of the expression evaluation you want to make:
A. In a String
Here, the CSS classes are listed in a string and separated by spaces, just like you would on any HTML element. The syntax look like this:
<some-element [ngClass]="'first second'">...</some-element>
B. In an Array
Just like the string, here you list the CSS classes in an array. Here is how the syntax looks:
<some-element [ngClass]="['first', 'second']">...</some-element>
C. In an Object
You can also define classes to be applied to an element with ngClass
in an object. The object keys will be the CSS classes that get added when the expression given in the value evaluates to true, otherwise they are removed. Here is how the syntax looks:
<some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>
Demo
If you followed this post from the start you would have downloaded and unzipped the Angular canvas from GitHub. Let us see how these work in a real Angular application that prints and styles tech courses in a university portal. Load up the app in your integrated development environment (I use VS Code), and open the app.component.html file and clean it up to look like this:
<div style="text-align:center">
<h1> Welcome to the Ghetto Tech University </h1>
</div>
<app-courses></app-courses>
<router-outlet></router-outlet>
To keep things modular, let’s create a new component and call it “courses”. In your terminal, run this command below:
ng generate component courses
Open your courses.component.ts
file and replace the code there with the code block below:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-courses',
templateUrl: './courses.component.html',
styleUrls: ['./courses.component.css']
})
export class CoursesComponent implements OnInit {
courses = [
{
'name': 'Introduction to Web Development',
'level': 'Beginner'
},
{
'name': 'Understanding APIs',
'level': 'Intermediate'
},
{
'name': 'Introduction to Docker Containers',
'level': 'Advanced'
},
{
'name': 'Understanding Time complexities',
'level': 'Advanced'
},
{
'name': 'Algorithms and Data Structures',
'level': 'Advanced'
},
{
'name': 'My first HTML page',
'level': 'Beginner
},
{
'name': 'Ways to use CSS in your web page',
'level': 'Beginner'
},
{
'name': 'Introduction to Unit testing',
'level': 'Intermediate'
},
{
'name': 'What are PWAs',
'level': 'Intermediate'
}
];
constructor() { }
ngOnInit() {
}
}
In this component, I created an array of objects of all the tech courses and their various levels for the semester. Next thing is to define the various styles that are needed for this exercise. Open up the courses.component.css file and paste the CSS rules below inside it:
.red{
color: red;
}
.green {
color: green;
}
.yellow {
color: blue;
}
.sizeup {
font-size: 25px;
}
Now for the presentation, go to the courses.component.html file and replace the placeholder content with the code block below inside it:
<p class="sizeup">
All <span [ngClass]="'green'">Beginner courses are colored green</span>, all <span class="yellow">intermediate courses are colored blue</span>
and all <span class="red">advanced courses are colored red</span>.
</p>
If you run the application now, you will see that the styles are all reflected, including the one with the ngClass
directive.
Using this same presentation code, let us see how it will fare if the definition is an array.
<p class="sizeup">
All <span [ngClass]="['green']">Beginner courses are colored green</span>, all <span class="yellow">intermediate courses are colored blue</span>
and all <span class="red">advanced courses are colored red</span>.
</p>
When you save it and look at your browser, your application remains the same, validating the array definition. Now to test out the object definition, let’s start with the very same example:
<p class="sizeup">
All <span [ngClass]="{'green': true}">Beginner courses are colored green</span>, all <span class="yellow">intermediate courses are colored blue</span>
and all <span class="red">advanced courses are colored red</span>.
</p>
This prints the paragraphs with the various colors assigned. To make this even more exciting, let’s now reference the courses we saved at the start:
<p class="sizeup">
All <span [ngClass]="{'green': true}">Beginner courses are colored green</span>, all <span class="yellow">intermediate courses are colored blue</span>
and all <span class="red">advanced courses are colored red</span>.
</p>
<ul>
<li *ngFor="let course of courses"
[ngClass]="{'green':course.level==='Beginner',
'yellow':course.level==='Intermediate',
'red':course.level==='Advanced',
'sizeup':true}">
{{ course.name }}
</li>
</ul>
Here we used the ngFor
directive to loop through the list and then with the ngClass
, we specified exactly that all the courses should be colored according to our predefined conditions (beginner courses in green, intermediate in blue and advanced courses in red). This was possible because the object key is of type boolean, so everything on the right side has to return true or false. Style gets applied if true, and does not apply when it returns false.
The complete code to this tutorial can be found here on GitHub.
Conclusion
This is one use case of the ngClass
directive. It can be used in a lot of scenarios, especially ones that require that you style an element based on some predefined logic. This post has introduced you to the world of conditional styling with ngClass
in Angular. Go forth and use it!