Using Angular ngClass directive you can dynamically add or remove CSS classes for a DOM element.
With ngClass the CSS classes can be provided in one of the following ways-
- string- The CSS classes listed in the string (space delimited) are added.
<some-element [ngClass]="'first second'">...</some-element>
- Array- The CSS classes declared as Array elements are added.
<some-element [ngClass]="['first', 'second']">...</some-element>
- Object- As a key, value pair where keys are CSS classes and values are conditions. CSS classes get added when the expression
given in the value evaluates to a truthy value, otherwise they are removed.
<some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element>
Angular ngClass directive example
Here is a simple example showing usage of ngClass. First add a CSS class.
app.component.css
.text-border { color: white; border: 1px dashed black; background-color: blue; }
Then in the template you can add <div> elements, one with value as true (so that CSS class is added) and one with value as false (so that CSS class is removed).
<div class="container"> <div [ngClass]="{'text-border': false}"> This text has no border </div> <div [ngClass]="{'text-border': true}"> This text has border </div> </div>
But you will see the real power of ngClass, just like with ngStyle directive, when the CSS class assignment happens dynamically.
Angular ngClass directive dynamic class assignment
In this example we’ll simulate a message for network transfer. There is a button “show status” that shows the current status of the network transfer. After few clicks if network transfer is still not done message is displayed in red color.
CSS used
.text-border { color: white; border: 1px dashed black; background-color: red; }
Component class
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { temp = []; onButtonClick(){ this.temp.push('Still transferring packet'); } }
Whenever button is clicked on the UI, onButtonClick() function is called which adds one more message to the array.
Template
<div class="container"> <button class="btn btn-primary" (click)="onButtonClick()"> Show Status </button> <div *ngFor="let t of temp; let i = index"> <span [ngClass]="{'text-border' : i > 5}">{{t}}</span> </div> </div>
In the template ngFor directive is used to iterate through the array of messages. Using ngClass directive CSS class ‘text-border’ is added dynamically when the iteration index is greater than 5.
That's all for this topic Angular ngClass Directive With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
You may also like-
No comments:
Post a Comment