When I use the following code to switch the class everything works fine
<p [ngClass]="idPresent ? 'alert alert-success' : 'alert alert-danger'">
Working
</p>
On changing the value of IdPresent
in the component, I can see the appropriate class being applied,
but when I use an object in the component for the same purpose it only works if idPresent
is false
. When I set the idPresent
to true
, the following code does not apply the appropriate class.
<p [ngClass]="idValueClass">
Not working
</p>
public idPresent = false;
public idValueClass = {
"alert alert-success" : this.idPresent,
"alert alert-danger" : !this.idPresent
};
Can someone help me figure out what am I doing wrong?
2
Answers
I believe that you mentioned the issue in which the "alert" class is removed.
From the documentation,
This results that the last "alert" was
false
and will be removed from the class.Modify the
idValueClass
as below:Demo @ StackBlitz
Updated
As raised by @Eliseo, if you have a button or logic to update the
idPresent
, theidValueClass
will not automatically reflect the latest value.You need a trigger/change event to overwrite the
idValueClass
.Or implement a getter for
idValueClass
(However it is not a good practice, Refer: Getter and setter in templates is a bad idea)i ever this problem before, i ever any key name class can be hidden like "success", "alert", "warning" etc with same case before. i try to make it single name class (alert-success") , not mutiple class ("alert alert-success") .
you can try this code as below =
i more suggestion condition on ngClass use tenary then get value on .ts