Angular 2 animate a specific targeted element

2019-09-14 01:31发布

问题:

I have 2 components:

  1. One which contain arouter-outlet where will be injected pages with a question and 3 possible answers

  2. Second that is a sort of preview, that contains 20 boxes I use a shared service(BehaviorSubject) for components communication

WHAT I DO IS THIS:

  • when user choose an answer from /question1 route, I use the service to emit a unique value(every answer have a unique value)
  • in the preview component I've subscribed to whatever service emits, and I know exactly what question is and what answer is submitted
  • now, accordingly to that specific answer I need to animate a specific box from this second component

MY QUESTION IS:

How do I apply a generic animation for that specific box. I don't want to create 20 different animations with different names, or 20 unique variables that will have true or false values. I want a way to target a box and apply my animation

回答1:

Animation is very easy to apply with Animate.css. Like, braindead easy. I know there's an Angular2-centric way of doing it with providers and the like (and I actually did it that way in one of my angular projects), but in another project I did it differently and found it to be easier and more flexible.

You download animate.css, bundle it into your build like any other CSS file, and you're done with setup. You can animate anything in your app just by dynamically applying classes via ngClass. You can change the animation on any element however you want based on any condition.

Say a button (for whatever reason) can be blue, or red. So you want the default animation to follow the button color. If the button changes color, you want the animation to change.

Easy.

<div [ngClass]="color === 'blue' ? 'animated pulse' : 'animated wobble'"
     ....></div>

Want to "reboot" the animation? Just reset the ngClass using a variable. When change detection kicks over, the new value will be applied.

<div [ngClass]="myAnimationVariable"
     ....></div> 

(where myAnimationVariable is something like "animated wobble" or whatever).

Anyway, I find it extremely easy, lightweight, and effective. I've heard a couple of times it's not the "pure angular" way, but that really doesn't matter to me. I'm bundling/parsing the CSS and using it in templates without directly accessing the DOM, that suits me fine.

Note you can also apply the classes to the nativeElement of a ViewChild. Works great. But that's walking the line of "accessing the DOM" (even though you are doing it through an Angular-gated mechanism), and may be frowned upon. But if it provides a solution and can be tested, then it's practical, so figured I'd point it out.