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.
- 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
- import { Component } from '@angular/core';
- @Component({
- selector: 'test-app',
- templateUrl: './app/directiveExample.html'
- })
- export class AppComponent {
- }
directiveExample.html
- <h4>1) Applying styles property</h4>
- <div>
- <div [style.color]="colorName">This is my Test String</div>
- <br/>
- <label>
- <input type="radio" name="test" value="red" [(ngModel)]="colorName" > Apply "Red" color
- </label>
- <br/>
- <label>
- <input type="radio" name="test" value="blue" [(ngModel)]="colorName"> Apply "Blue" color
- </label>
- <br/>
- <label>
- <input type="radio" name="test" value="gray" [(ngModel)]="colorName"> Apply "Gray" color
- </label>
- </div>
Output
- 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
- import { Component } from '@angular/core';
- @Component({
- selector: 'test-app',
- templateUrl: './app/directiveExample.html',
- styleUrls: ['./app/componentStyle.css']
- })
- export class AppComponent {
- }
componentStyle.css
- .italic { font-style: italic; }
- .bold { font-weight: bold; }
- .error { color: red; }
directiveExample.html
- <h4>2) Use ngClass directive</h4>
- <div>
- <div [ngClass]="{italic: italic, bold: bold, 'error': error}">This is my ngClass Test</div>
- <br />
- <label>
- <input type="checkbox" [(ngModel)]="italic"> Apply "italic" class </label>
- <br>
- <label>
- <input type="checkbox" [(ngModel)]="bold"> Apply "bold" class </label>
- <br>
- <label>
- <input type="checkbox" [(ngModel)]="error"> Apply "Error" class </label>
- </div>
Output
- 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.
Example - In 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
- <h4>3) Adding single class</h4>
- <div>
- <div [class.italic]="italicSelected" [class.bold]="boldSelected" [class.error]="errorSelected" >This is my ngClass Test</div>
- <br />
- <label>
- <input type="checkbox" [(ngModel)]="italicSelected"> Apply "italic" class </label>
- <br>
- <label>
- <input type="checkbox" [(ngModel)]="boldSelected"> Apply "bold" class </label>
- <br>
- <label>
- <input type="checkbox" [(ngModel)]="errorSelected"> Apply "Error" class </label>
- </div>
- 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
- import {Directive, ElementRef, Renderer} from '@angular/core';
-
- @Directive({
- selector: '[myStyle]',
- })
- export class MyStyleDirective {
- constructor(public el: ElementRef, public renderer: Renderer) {
- renderer.setElementStyle(el.nativeElement, 'color', 'red');
- }
- }
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
- import { NgModule } from '@angular/core';
- import { BrowserModule } from '@angular/platform-browser';
- import { FormsModule } from '@angular/forms';
-
- import { AppComponent } from './app.component';
- import { MyStyleDirective } from './styleComponent';
-
- @NgModule({
- imports: [ BrowserModule, FormsModule],
- declarations: [ AppComponent, MyStyleDirective],
- bootstrap: [ AppComponent ]
- })
- export class AppModule {
- }
app.component.ts
- import { Component } from '@angular/core';
-
- import { MyStyleDirective } from './styleComponent';
-
- @Component({
- selector: 'test-app',
- templateUrl: './app/directiveExample.html',
- styleUrls: ['./app/componentStyle.css']
- })
- export class AppComponent {
- }
directiveExample.html
- <h4>4) By creating custom Directive</h4>
- <div>
- <div myStyle> Hello Reader!!! This is Test Text </div>
- </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.