ANGULAR
Complete Angular Tutorial For Beginners Introduction to Angular | What is Angular? Architecture Overview & Concepts of Angular How to Install Angular How to Create a new project in Angular Bootstrapping in Angular: How It Works Internally Angular Components Overview & Examples Data Binding in Angular Interpolation in Angular Property Binding in Angular Event Binding in Angular ngModel & Two way Data binding in Angular NgModelChange & Change Event in Angular Child/Nested Components in Angular angular directives angular ngFor directive ngSwitch, ngSwitchcase, ngSwitchDefa ult Angular Example How to use ngIf, else, then in Angular By example NgClass Example Conditionally apply class Angular ngStyle Directive Angular Trackby to improve ngFor Performance How to Create & Use Custom Directive In Angular Working with Angular Pipes How to Create Custom Pipe in Angular Formatting Dates with Angular Date Pipe Using Angular Async Pipe with ngIf & ngFor angular keyValue pipe Using Angular Pipes in Components or Services Angular Component Communication & Sharing Data Angular Pass data to child component Angular Pass data from Child to parent component Component Life Cycle Hooks in Angular Angular ngOnInit And ngOnDestroy Life Cycle hook Angular ngOnChanges life Cycle Hook Angular ngDoCheck Life Cycle Hook Angular Forms Tutorial: Fundamentals & Concep t s Angular Template-driven forms example How to set value in template-driven forms in Angular Angular Reactive Forms Example Using Angular FormBuilder to build Forms SetValue & PatchValue in Angular StatusChanges in Angular Forms ValueChanges in Angular Forms FormControl in Angular FormGroup in Angular Angular FormArray Example Nested FormArray Example Add Form Fields Dynamically SetValue & PatchValue in FormArray Angular Select Options Example in Angular Introduction to Angular Services Introduction to Angular Dependency Injection Angular Injector, @Injectable & @Inject Angular Providers: useClass, useValue, useFactory & useExisting Injection Token in Angular How Dependency Injection & Resolution Works in Angular Angular Singleton Service ProvidedIn root, any & platform in Angular @Self, @SkipSelf & @Optional Decorators Angular '@Host Decorator in Angular ViewProviders in Angular Angular Reactive Forms Validation Custom Validator in Angular Reactive Form Custom Validator with Parameters in Angular Inject Service Into Validator in Angular template_driven_form_validation_in_angular Custom Validator in Template Driven Forms in Angular Angular Async Validator Example Cross Field or Multi Field Validation Angular How to add Validators Dynamically using SetValidators in Angular Angular HttpClient Tutorial & Example Angular HTTP GET Example using httpclient Angular HTTP POST Example URL Parameters, Query Parameters, httpparams in Angular HttpClient Angular HTTPHeaders Example Understanding HTTP Interceptors in Angular Angular Routing Tutorial with Example Location Strategy in Angular Angular Route Params Angular : Child Routes / Nested Route Query Parameters in Angular Angular Pass Data to Route: Dynamic/Static RouterLink, Navigate & NavigateByUrl to Navigate Routes RouterLinkActive in Angular Angular Router Events ActivatedRoute in Angular Angular Guards Tutorial Angular CanActivate Guard Example Angular CanActivateChild Example Angular CanDeactivate Guard Angular Resolve Guard Introduction to Angular Modules or ngModule Angular Routing between modules Angular Folder Structure Best Practices Guide to Lazy loading in Angular Angular Preloading Strategy Angular CanLoad Guard Example Ng-Content & Content Projection in Angular Angular @input, @output & EventEmitter Template Reference Variable in Angular ng-container in Angular How to use ng-template & TemplateRef in Angular How to Use ngTemplateOutlet in Angular '@Hostbinding and @Hostlistener_in_Angular Understanding ViewChild, ViewChildren &erylist in Angular ElementRef in Angular Renderer2 Example: Manipulating DOM in Angular ContentChild and ContentChildren in Angular AfterViewInit, AfterViewChecked, AfterContentInit & AfterContentChecked in Angular Angular Decorators Observable in Angular using RxJs Create observable from a string, array & object in angular Create Observable from Event using FromEvent in Angular Using Angular observable pipe with example Angular Map Operator: Usage and Examples Filter Operator in Angular Observable Tap operator in Angular observable Using SwitchMap in Angular Using MergeMap in Angular Using concatMap in Angular Using ExhaustMap in Angular Take, TakeUntil, TakeWhile & TakeLast in Angular Observable First, Last & Single Operator in Angular Observable Skip, SkipUntil, SkipWhile & SkipLast Operators in Angular The Scan & Reduce operators in Angular DebounceTime & Debounce in Angular Delay & DelayWhen in Angular Using ThrowError in Angular Observable Using Catcherror Operator in Angular Observable ReTryWhen inReTry, ReTryWhen in Angular Observable Unsubscribing from an Observable in Angular Subjects in Angular ReplaySubject, BehaviorSubject & AsyncSubject in Angular Angular Observable Subject Example Sharing Data Between Components Angular Global CSS styles View Encapsulation in Angular Style binding in Angular Class Binding in Angular Angular Component Styles How to Install & Use Angular FontAwesome How to Add Bootstrap to Angular Angular Location Service: go/back/forward Angular How to use APP_INITIALIZER Angular Runtime Configuration Angular Environment Variables Error Handling in Angular Applications Angular HTTP Error Handling Angular CLI tutorial ng new in Angular CLI How to update Angular to latest version Migrate to Standalone Components in Angular Create Multiple Angular Apps in One Project Set Page Title Using Title Service Angular Example Dynamic Page Title based on Route in Angular Meta service in Angular. Add/Update Meta Tags Example Dynamic Meta Tags in Angular Angular Canonical URL Lazy Load Images in Angular Server Side Rendering Using Angular Universal The requested URL was not found on this server error in Angular Angular Examples & Sample Projects Best Resources to Learn Angular Best Angular Books in 2020

NgClass Example Conditionally apply class

The Angular ngClass Directive is an Angular Attribute Directive, which allows usto add or remove CSS classes to an HTML element. ngClass makes adding a conditional class to an element easier, hence dynamically changing the styles at runtime. We can also add multiple CSS Classes.

NgClass

The ngClass is a directive that Angular uses to dynamically add or remove CSS classes to an HTML element based on certain conditions.

                              
 
<element [ngStyle]="{'styleNames': styleExp}">...</element>
                            
                        
Where

The element is the DOM element to which we want to apply the CSS class.

The expression, when evaluated, must return a String, Array, or object. The ngClass Directive extracts the class name from the result and applies it to the element.

Let us explore all of them with examples.

ngClass Examples

Create a new angular project using ng new. Empty the app.component.html. Open the app.component.css with the following CSS styles.

                              
 
.primary {
  color: red;
}
.secondary {
  color: green;
}
 
.big {
  font-size: 20px;
}
 
.small {
  font-size: 12px;
}
 
.italics {
  font-style: italic;
}
 
.is-active {
  font-weight: bolder;
}
.section {
  margin: 10px;
}
 
                            
                        

You can view the source code from StackBlitz.

NgClass with a String

You can use the string as an expression and bind it directly to the ngClass attribute. If you want to assign multiple classes, separate each with space, as shown below.

                              

<element [ngClass]="'cssClass1 cssClass2'">...</element>
 
                            
                        

Add the following to the app.template.html.

                              

//Example 1
<div [ngClass]="'primary big'">Sample Text</div>
                            
                        

The above example code adds the multiple CSS Classes,primary & big, to the div element.

You can also use the ngClass without a square bracket. In that case, the expression is not evaluated but assigned directly to the class attribute. As shown below, we must remove the double quote around the expression.

                              
 
 //Example 2
<div ngClass="primary big">Sample Text</div> 
                            
                        

NgClass with Array

If the ngClass expression returns an array, Angular treats each array element as a CSS class.

The syntax is as follows.

                              
 
<element [ngClass]="['cssClass1', 'cssClass2']">...</element>
                            
                        

This example below, passes the array with two elements.ngClass will treat each element as a class. The following code applies primary and big classes to the div element.

                              
 
<div [ngClass]="['primary', 'big']">Sample Text</div>
                            
                        

If there is a space between the string of an element, then both will be treated as a separate class. For example, in the code below, the array element at index 0 has the value primary big. It will treat this as two different classes.

                              

<div [ngClass]="['primary big','italics']">Sample Text</div>
                            
                        

NgClass with Object

You can also bind the ngClass to an object. The properties (keys) of the object will act as a class name. The properties must return a boolean value. If the return value is true, the class is applied. Else not.

The syntax is as follows.

                              

<element [ngClass]="{'cssClass1': true, 'cssClass2': true}">...</element>
 
                            
                        

If the property name contains spaces, it will treat it as two classes. But you need to use quotes around the property name. Quotes are also required if the class name has - etc.

In the example below, an object is bound to the ngClass. The object has two properties, primary and big. Since both return true,ngClass will apply both classes to the element.

                              

<div [ngClass]="{ primary: true, big: true }">Sample Text</div>
                            
                        

The first property in the code below (primary italics) has a space.ngClass will treat it as two separate classes. Hence it will apply three classes,primary,italics & big, to the element.

                              

<div [ngClass]="{ 'primary italics': true, big: true }">Sample Text</div>
                            
                        

The property is-active has a –. Hence use the quote; else, it will result in an error.

                              

<div [ngClass]="{ 'is-active': true, big: true }">Sample Text</div>
                            
                        

Applying class from component

We can dynamically change the CSS Classes from the component.

Create the following variable in the component class.

                              

  cssVar: string = 'primary big';
  cssArray = ['primary', 'big'];
  cssClass = {
    primary: true,
    big: true,
  };
 
                            
                        

We can use them in the Template.

                              

  <b>Example 5: Value comming from the component method</b> <br />
  <b>Example 5A (string)</b> <br />
  <div [ngClass]="cssVar">Sample Text</div>
 
  <b>Example 5B (array)</b> <br />
  <div [ngClass]="cssArray">Sample Text</div>
 
  <b>Example 5C (Object)</b> <br />
  <div [ngClass]="cssClass">Sample Text</div>
 
                            
                        

You can modify the variables anytime; the view will reflect these changes.

The ngClass Directive switches the CSS class based on the flag‘s value.

                              

  <div [ngClass]="flag ? 'primary' : 'secondary'">
    Sample Text
    <button (click)="flag = !flag">Change Color</button>
  </div>
 
                            
                        

Conditionally applying class

One of the most important use cases of ngClass is we can conditionally apply the CSS classes.

For example, add the following code in the component class. The getClass return primary if the value of num is less than 50 and secondary otherwise.

                              

 numbers = [30, 40, 50, 60, 70, 80];
  getClass(num) {
    if (num <= 50) return 'primary';
    else return 'secondary';
  }
 
                            
                        

In the HTML template, we use ngFor to loop over the numbers array and display the list. We invoke the getClass method and assign the return value to ngClass Directive.

                              

  <ul>
    <li *ngFor="let num of numbers">
      <div [ngClass]="getClass(num)">{{ num }}</div>
    </li>
  </ul>
 
                            
                        

You can write the expression in the Template itself, as shown below.

                              

  <ul>
    <li *ngFor="let num of numbers">
      <div [ngClass]="{ primary: num <= 50, secondary: num > 50 }">
        {{ num }}
      </div>
    </li>
  </ul>
 
                            
                        

Vs. Class

You can also set CSS classes using the ClassName property or class binding. But ngClass is more flexible and is the preferred method.

You can view the source code from StackBlitz.

Summary

  • ngClass is used the add conditional class to a HTML element.
  • The syntax is <element>,<ngClass> <expression> []=""...<element>
  • The expression must return a string, array, or object.