Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

attr - Angular 2+ Can you add/remove a CSS class based on html data property?

First I would like to add a little more context to the question.

Right now I have the following:

I want to make it more dynamic by removing the need to have a property in the class and just add a data property to the html element, in hopes that I can manage it's state using said property.

This whole idea might be wrong, so if there is another way to achieve this, please guide me into the right direction.

Thank you!

UPDATE

After some thinking I changed my approach a bit, instead of relying on the component property I added to each element a new [attr.data-visible] property with a default "false" value. Then on the mouseover event I added a method that gets the html element as a parameter and then changes the data-visible value from false to true, and vice versa on the mouseout event.

Here is a working StackBlitz


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Demo you can do it with ngClass and events.

 [ngClass]="{'your_class': isHovered}"
 (mouseover)="isHovered=true"
 (mouseout)="isHovered=false"

If you have an array object and do it inside them then give property to each object in array

 [ngClass]="{'your_class': data.isHovered}"
    (mouseover)="data.isHovered=true"
    (mouseout)="data.isHovered=false"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...