It is used to add or remove CSS classes dynamically (run-time) from a DOM Element.
- ngClass with string
- ngClass with array
- The ngClass with object
- ngClass with component method
Applying multiple css classes with ngClass Directive:
note:
-----
*ngClass directive is deprecated with Angular4,the alternative is class directive
...
<h3 [class]="cssclassname">result:{{res}}</h3>
Example
class directive allows applying CSS class based on Boolean type, where as it is
not supported by ngclass directive
syntax:
<tagname [class.cssclassname]="true|false">..</tagname>
true-it will apply CSS class to html element
false-it will remove CSS class from html element
.html
<style>.c1{background-color: black;color:white;border:5px solid yellow;width:30%;padding: 10px;margin: 20px;}</style><h2 [class.c1]="flag">Rajakonda Uday Kumar</h2><br><input type="checkbox" [(ngModel)]="flag">Apply CSS.tsimport { Component } from '@angular/core';@Component({selector: 'app-classbindingexample',templateUrl: './classbindingexample.component.html',styleUrls: ['./classbindingexample.component.css']})export class ClassbindingexampleComponent {flag:boolean=false;}Output
ngClass with Array:
This is very much similar to the previous example i.e. applying multiple css classes. The difference is only the way you applying the css classes. The syntax to use ngClass with Array is given below. Here, you need to use one square bracket and then you need to specify the classes in a single quotes separated by a comma.
style binding-->single characteristic
textcolor,showhide variables
==>complex with style binding
<h2 [style.color]="textcolor" |
[style.visibility]="showhide">res..</h2> the solution is ngstyle
ngstyle -->multiple characteristics
mystyle={"color":..,"visibility":..}; ==>simple
<h2 [style]="mystyle">..</h2>
ngclass --> styling based on css classes