1

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?

1
  • Note That: This class is not applied in the div where the condition check exists Commented Dec 14, 2020 at 8:39

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.