AngularJS (67 Blogs) Become a Certified Professional

NgClass in Angular with Examples

Last updated on Oct 05,2024 11.2K Views

5 / 6 Blog from Angular Basics

Angular has emerged as one of the most widely accepted front-end development frameworks. A major reason for this was the simplicity provided for performing trivial tasks, that would generally take a lot of time when using vanilla JavaScript. One such feature is the usage of directives in AngularJS. In this particular blog, we will be looking into the ngClass directive. The following topics are covered in this blog:

What is ngClass?

ngClass is a directive. It is Angular’s way of allowing you to use different classes and styles based on what’s happening in your angular-component. While CSS covers many scenarios with pseudo-classes, you’ll often run into scenarios where you need to apply classes based on certain conditions. This is where ngClass comes to the rescue.

If you would like to learn more about angular, and gear your career towards a proficient angular developer, then consider enrolling for our Angular Certification Training Course

What are Directives?

Angular logo

Directives are markers on a DOM element that tell Angular to attach a specified behavior to that DOM element or even transform the DOM element and its children. In short, it extends to HTML. Most of the directives in Angular start with ng- where ng stands for Angular. Angular includes various built-in directives. In addition to this, you can create custom directives for your application. ngClass comes under built-in directives.

How to Use the ngClass Directive

The ng-class directive dynamically binds one or more CSS classes to an HTML element. The value of the ng-class directive can be a string, an object, or an array. If it is a string, it should contain one or more, space-separated class names. As an object, it should contain key-value pairs, where the key is the class name of the class you want to add, and the value is a boolean value. The class will only be added if the value is set to true. Implemented as an array, it can be a combination of both. Each array element can be either a string or an object, described as above.

The following are the examples of how to use ngClass Directive.

  • ngClass as a String

Here, I will discuss an example of how to use ng-class as a String. First things first, let’s add a title or header to our HTML Page. For this, you need to type the following code in your app.component.html file.

<mat-toolbar>
    <h1>Welcome to {{title}}!</h1>
</mat-toolbar>

Here, <mat-toolbar> is a container from Angular Material that is used for headers and titles. In case, you are not familiar with it, you can refer to the article on Angular Material for the installation and a demo tutorial.

Next, you need to serve your project using the following command:

ng serve -o

This will open your project on the default browser of your system as shown below:

Toolbar Page - ngClass - Edureka

Now, you need to add certain CSS classes in your app.component.css file.

.first {
    background-color: #3471eb;
}

.second {
    font-size: 30px;
    padding-left: 20px;
}

To bind these classes in an HTML element, you need to type the following code in your app.component.html file:

&lt;div [ngClass]="'first'"&gt;
    &lt;p [ngClass]="'second'"&gt;ngClass as a String&lt;/p&gt;
&lt;/div&gt;

To bind a CSS class to [ngClass], it must be enclosed in a single quote (‘), as shown above. Now, you need to serve your project to display the output.

You can even bind two or more CSS classes in one [ngClass], to use the properties of the classes bound. For example, you need to add the following classes in your app.component.css file. 

.third {
    height: 10%;
}

.fourth {
    padding-top: 20px;
}

Next, you need to bind the above CSS classes in [ngClass], located in your app.component.html file. 

&lt;div [ngClass]=&rdquo;&rsquo;first second third&rsquo;&rdquo;&gt;
    &lt;p [ngClass]="'fourth'"&gt;ngClass as a String&lt;/p&gt;
&lt;/div&gt;

Later, you need to serve your project to display the following output.

  • *ngFor Directive in a String

    Now, let me show you another example using *ngFor Directive. *ngFor is a template directive in Angular to iterate over elements declared in an array or an object. And later, it creates a template for each item. Moving ahead, you need to first declare an array inside the following class, located in the app.component.ts file. 

export class AppComponent {
    users = [
        &lsquo;Edureka&rsquo;,
	&lsquo;Angular&rsquo;,
	&lsquo;ngClass&rsquo;
    ];
}

Next, you need to add the following class in your app.component.css file. 

.fifth {
    color: red;
    font-size: 25px;
    padding-left: 20px;
}

Followed by this, you need to bind the above class in [ngClass], located in your app.component.html file.


&lt;div *ngFor=&rdquo;let user of users&rdquo; [ngClass]=&rdquo;&rsquo;fourth fifth&rsquo;&rdquo;&gt;
	{{user}}
&lt;/div&gt;



Later, you need to serve your project to display the output.

ngClass String Third - ngClass - Edureka

 

  • ngClass as an Array

Here, I will discuss an example of how to use ng-class as an Array. Basically, there are no changes in the properties of CSS classes bound in ng-class as a String. It is just that the CSS classes are bound as an Array. Let’s see an example for your better understanding. You need to type the following code in your app.component.html file. 

&lt;div [ngClass]=&rdquo;[&rsquo;first&rsquo;, &lsquo;second&rsquo;, &lsquo;third&rsquo;]&rdquo;&gt;
    &lt;p [ngClass]="['fourth']"&gt;ngClass as an Array&lt;/p&gt;
&lt;/div&gt;

The CSS classes are enclosed in [ ] brackets when declared as an Array. Let’s serve the project now to see the result. 

As you see above, there are no changes in the properties of CSS classes, except for the classes bound in an Array.

  • ngClass as an Object

Moving ahead, I will discuss an example of how to use ng-class as an Object. This is like a boolean value, that evaluates a CSS Class Property when returned true. Otherwise, it does not evaluate the CSS Class Property when it returns false

You need to type the following code in your app.component.html file.

&lt;div [ngClass]=&rdquo;{&rsquo;first&rsquo;: true}&rdquo;&gt;
    &lt;p [ngClass]="{'second': false}"&gt;ngClass as an Object&lt;/p&gt;
&lt;/div&gt;

In the above code, only the ‘first’ CSS class will be evaluated as it returned true but not the ‘second’ CSS class as it returned false. Let’s see another example for better understanding.

&lt;div [ngClass]=&rdquo;{&rsquo;first&rsquo;: false, &lsquo;second&rsquo;: true, &lsquo;third&rsquo;: true}&rdquo;&gt;
    &lt;p [ngClass]="{'fourth': false}"&gt;ngClass as an Object&lt;/p&gt;
&lt;/div&gt;

Now, you need to serve your project to display the output.


ngClass Object - ngClass - Edureka

Learn  about Angular dropdown menu and ngmodel in angular

Want to create great mobile apps? A Flutter App Developer Course is a great place to start.

Unleash your creativity and build stunning websites with our Web Developer Course.

Unleash your creativity and design skills with our UI and UX Design Course.

Got a question for us? Please mention it in the comments section of this “Angular ng-class” and we will get back to you.

Upcoming Batches For Angular Certification Training Course Online
Course NameDateDetails
Angular Certification Training Course Online

Class Starts on 21st December,2024

21st December

SAT&SUN (Weekend Batch)
View Details
Angular Certification Training Course Online

Class Starts on 15th February,2025

15th February

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

NgClass in Angular with Examples

edureka.co