MisterniceGuy
MisterniceGuy

Reputation: 1796

How can i use *ngif in angular to change div class

I have the need to change the class of a div based on some condition. How can i use *ngif to achieve that ? I use this code which works fine in my template.

<div *ngIf="quickSearchTypeOptionConfigId && isGridReady" class="col-md-4 m-auto">

But i have a div above this div which is currently

<div class="col-md-8 m-auto"> 

What my need this to be is if *ngIf="quickSearchTypeOptionConfigId && isGridReady" true true then

<div class="col-md-8 m-auto">

else

<div class="col-md-12 m-auto">

is there a way to do this other then do 2 *ngif's

Upvotes: 2

Views: 12635

Answers (4)

Nickolaus
Nickolaus

Reputation: 4835

Pretty simple:

  • [class.myClass]="condition" or
  • [style.attribute]="condition" / [style.attribute.unit]="condition" or
  • [ngClass]="condition ? 'ifConditionClass' : 'elseConditionClass' (or empty string)"

Upvotes: 1

Steve
Steve

Reputation: 1943

You can use the ngClass attribute to check for conditions and assign CSS classes based on the result.

<div [ngClass]="{[quickSearchTypeOptionConfigId && isGridReady] ? 'col-md-8 m-auto' : 'col-md-12 m-auto'"}"></div>

Upvotes: 1

User2585
User2585

Reputation: 372

This should work for you [ngClass]="(quickSearchTypeOptionConfigId && isGridReady)?'col-md-8 m-auto':'col-md-12 m-auto'"

Upvotes: 8

Nadhir Falta
Nadhir Falta

Reputation: 5257

You will have to use ngClass like this:
[ngClass]="[quickSearchTypeOptionConfigId && isGridReady ? 'col-md-8 m-auto' : 'col-md-12 m-auto']"

Upvotes: 4

Related Questions