Wagdy Samih
Wagdy Samih

Reputation: 31

Change CSS style in a specific class conditionally in angular+2

let's assume that I have a class

.some-class{
   /// some style ex:
   display: none
}

I want to target that specific class to change the style to

.some-class{
   display: block
}

based on some user action in my application so it be something like this

<div [class.some-class]="condition? display: block" >

</div>

is that possible without the need of using JavaScript DOM?

Upvotes: 1

Views: 4229

Answers (1)

Pradyumna Pasumarty
Pradyumna Pasumarty

Reputation: 201

If your intention is to apply styles conditionally it would be better to declare 2 classes in styles and then use the [ngClass] feature that Angular offers to apply your class conditionally. Ref: https://angular.io/api/common/NgClass

.some-class__success{
  display: block;
}

.some-class__normal{
  display: none;
}

<div [ngClass]="condition ? 'some-class__success' : 'some-class__normal'">

</div>

Thus, you can have [ngClass] on multiple tags based on the same condition. But the classes written for those conditions can be changed as per your requirement for each tag.

I suggest this approach because it is usually not recommended and is in fact a bit of hassle to change the contents of css classes based on conditions in HTML or JS.


If your intention is to conditionally show/hide a div, its much easier to use the super-easy *ngIf. Ref: https://angular.io/api/common/NgIf

*ngIf only renders an element if the condition is true.

.some-class{
  display: block;
}  

<div class="some-class" *ngIf="condtion">
  I'm shown only if condition is true!
  My class would be some-class!
</div>

This is the recommended approach for hiding/showing elements because it simply doesnt render a tag if a condition is false. So no extra styles are needed and more importantly, unexpected functions or calls can't originate from an un-rendered element, making your code error free and easy to debug.

Upvotes: 3

Related Questions