Conditionally Add Styles To HTML Element In Angular 2

Introduction

In our day-to-day programming with Angular 2, we have a constant requirement to change the style of an HTML element conditionally. There are multiple ways to do this. In this article, we will learn the different ways of conditionally applying styles to a DOM element in Angular 2.

The following are the ways to conditionally apply styles to a DOM element in Angular 2.

  1. Applying styles property

    Angular 2 allows us to assign the style property of HTML element. The syntax of assigning property is -

    [style.propertyname.subpropertyname] = 'expression'


    Here, the expression can be anything, either a property of component, or an expression, or a method return value.

    Example - In the following example, I am assigning “color” property of element based on the radio button selected.

    App.component.ts
    1. import { Component } from '@angular/core';  
    2. @Component({  
    3.   selector: 'test-app',  
    4.   templateUrl: './app/directiveExample.html'  
    5. })  
    6. export class AppComponent {   

    directiveExample.html
    1. <h4>1) Applying styles property</h4>  
    2. <div>    
    3.     <div [style.color]="colorName">This is my Test String</div>  
    4.     <br/>  
    5.      <label>    
    6.         <input type="radio" name="test" value="red" [(ngModel)]="colorName" > Apply "Red" color   
    7.     </label>    
    8.     <br/>    
    9.     <label>    
    10.         <input type="radio" name="test"  value="blue" [(ngModel)]="colorName"> Apply "Blue" color    
    11.     </label>    
    12.     <br/>    
    13.     <label>    
    14.         <input type="radio" name="test"  value="gray" [(ngModel)]="colorName"> Apply "Gray" color    
    15.     </label>   
    16. </div> 
    Output



  2. Use ngClass directive

    Angular 2 still supports ngClass directive. This is a good and straight forward way to conditionally change the stylesheet class. The ngClass directive allows us to pass an object (key: value) where the key represents the CSS class and the value represents a Boolean condition whether a specific class is applied to the element or not.

    Example - In the following example, I have created three CSS classes and applied the style to the HTML element based on the checkbox selection. Here, I have created separate file for CSS class, and included it into component class.

    App.component.ts
    1. import { Component } from '@angular/core';  
    2. @Component({  
    3.   selector: 'test-app',  
    4.   templateUrl: './app/directiveExample.html',  
    5.   styleUrls: ['./app/componentStyle.css']  
    6. })  
    7. export class AppComponent {   

    componentStyle.css
    1. .italic { font-style: italic;  }  
    2. .bold { font-weight: bold; }  
    3. .error { color: red; } 
    directiveExample.html
    1. <h4>2) Use ngClass directive</h4>  
    2. <div>  
    3.     <div [ngClass]="{italic: italic, bold: bold, 'error': error}">This is my ngClass Test</div>    
    4.     <br />    
    5.     <label>    
    6.         <input type="checkbox" [(ngModel)]="italic"> Apply "italic" class </label>    
    7.     <br>    
    8.     <label>    
    9.         <input type="checkbox" [(ngModel)]="bold"> Apply "bold" class </label>    
    10.     <br>    
    11.     <label>    
    12.         <input type="checkbox" [(ngModel)]="error"> Apply "Error" class </label>    
    13. </div> 
    Output



  3. Adding single class

    Angular 2 also provides an alternative of ngClass, especially in situations when only a single class needs to be applied on HTML element. Using the following syntax, we can assign the class to the HTML element conditionally.

    [class.nameOfClass] = 'someCondition'

    Here, 'someCondition' must have value true or false. Based on that value, Angular 2 applies or removes the class on the HTML element.

    ExampleIn the following example, I have used [class.italic], [class.bold], [class.error]. And, based on the user selection, CSS classes are applied on the HTML element.

    Here, the component definition and the output is same as the above method.

    directiveExample.html
    1. <h4>3) Adding single class</h4>  
    2. <div>  
    3.     <div [class.italic]="italicSelected" [class.bold]="boldSelected" [class.error]="errorSelected" >This is my ngClass Test</div>    
    4.     <br />    
    5.     <label>    
    6.         <input type="checkbox" [(ngModel)]="italicSelected"> Apply "italic" class </label>    
    7.     <br>    
    8.     <label>    
    9.         <input type="checkbox" [(ngModel)]="boldSelected"> Apply "bold" class </label>    
    10.     <br>    
    11.     <label>    
    12.         <input type="checkbox" [(ngModel)]="errorSelected"> Apply "Error" class </label>    
    13. </div> 
  4. By creating custom Directive

    The last possibility is to inject the change to the DOM element by creating custom directive. In the following example, I have created a directive named as "myStyle", which is added to the div element.

    Following is the definition of the "myStyle" directive. Here, I have used ElementRef and Renderer into the directive constructor. The "ElementRef" allows us to access the native element via API and "Renderer" provides us the abstraction over the native elements.

    styleComponent.ts
    1. import {Directive, ElementRef, Renderer} from '@angular/core';  
    2.   
    3. @Directive({  
    4.   selector: '[myStyle]',  
    5. })  
    6. export class MyStyleDirective {  
    7.   constructor(public el: ElementRef, public renderer: Renderer) {  
    8.     renderer.setElementStyle(el.nativeElement, 'color''red');  
    9.   }  

    Here, we have added the directive, so we need to register it into the application module and import it to the component in which we are going to use this directive.

    App.module.ts
    1. import { NgModule }      from '@angular/core';  
    2. import { BrowserModule } from '@angular/platform-browser';  
    3. import { FormsModule } from '@angular/forms';  
    4.   
    5. import { AppComponent }  from './app.component';  
    6. import { MyStyleDirective } from './styleComponent';  
    7.   
    8. @NgModule({  
    9.   imports:      [ BrowserModule, FormsModule],  
    10.   declarations: [ AppComponent, MyStyleDirective],  
    11.   bootstrap:    [ AppComponent ]  
    12. })  
    13. export class AppModule {   

    app.component.ts
    1. import { Component } from '@angular/core';  
    2.   
    3. import { MyStyleDirective } from './styleComponent';  
    4.   
    5. @Component({  
    6.   selector: 'test-app',  
    7.   templateUrl: './app/directiveExample.html',  
    8.   styleUrls: ['./app/componentStyle.css']  
    9. })  
    10. export class AppComponent {   

    directiveExample.html
    1. <h4>4) By creating custom Directive</h4>  
    2. <div>  
    3.     <div myStyle> Hello Reader!!! This is Test Text </div>     
    4. </div> 
    Output


I think, this is very long way to apply style to the element.

Conclusion

In this article, we learned about applying the style to our DOM element in Angular 2, based on condition and also learned applying the style to the element by creating custom directive.

Note - Here, I have not included the dependency of the example project. To run the project, you need to perform "npm install" command to download the project dependency.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now