Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 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 Reply

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...