Sitemap

Angular — Attribute Directives : ngClass, ngStyle

Jan 11, 2023

--

Detailed explanation and syntax about ngClass, ngStyle

ngClass

1. Applying single Class

[ngClass]=" 'text-primary' "    

2. Applying Multiple Class properties

[ngClass]=" [ 'text-primary', 'text-danger'] "

3. Applying based on conditions

[ngClass] = " { 'text-primary': true, 'text-danger': 20<10 } "

4. Applying to multiple classes

[ngClass]=" { 'class1 class2 class3' : true} "

5. Applying based on [ class.className]

Get ashin s raj’s stories in your inbox

Join Medium for free to get updates from this writer.

[class.text-primary] = "score1 > score2"

ngStyle

Basic Syntax

<div [ngStyle]="{'background-color':'green'}"></<div>
<div [ngStyle]="{backgroundColor:'green'}"></<div>  //used CamelCase format

Using Conditions

<div [ngStyle]="{'background-color':person.country === 'UK' ? 'green' : 'red' }"></<div>

Alternative Syntax

<ul *ngFor="let person in people>
<li [style.color]="getColor(person.country)"></li>
</ul>
<p [style.color]="'red'"> This a Long paragraph</p>
// #note '' is used inside "" for the proper working
<div class="col-xs-12"
[style.background-color]="'magenta'">
</div>

--

--

ashin s raj
ashin s raj

Written by ashin s raj

here to make web a better place for everyone