How to conditionally add animation in Angular 2

I have a form component that has fields, some fields that I want to animate when they appear on the form, but not every field.

<div *ngFor="let field of form.Fields"> <div [ngSwitch]="field.Type" [@slideOut]> <!-- more field stuff --> </div> </div> 

With other attributes, I can do something like this [attr.required]="field.Required" But [ attr.@slideOut ] does not seem to work.

Ideally, I would like to have an animation property in my field so that I can transfer animations like this [@field.Animation] , but I cannot find any documentation on how I will do something like this. Any ideas?

+5
source share
1 answer

I ran into a similar problem and found that you need to take a slightly different approach.

In Angular, animations are state related. Therefore, instead of defining a different trigger for your animation in your HTML, you want to define several states that your trigger can observe in your component class. And instead of starting the animation directly from the method, you set the state of the object that the animation is associated with.

So, for example, I could define the following in the component decorator after importing the necessary modules.

 @Component({ selector: 'app-some-animated', templateUrl: './some.component.html', styleUrls: ['./some-animated.component.scss'], animations: [ trigger('flyInOut', [ transition("void => fly", [ animate(300, keyframes([ style({transform: 'translateX(100%)', opacity: 0}), style({transform: 'translateX(0)', opacity: 1}) ])) ] ) ]), trigger('flyInOut', [ transition("void => fade", [ animate(300, keyframes([ style({opacity: 0}), style({opacity: 1}) ])) ] ) ]) ] }) 

In this case, I am doing the animation as soon as the item is created. And in the ngOnInit () method, I set this.watchMe to "fly" or "fade".

In html, I attach the flyInOut trigger as follows:

 <div [@flyInOut]="watchMe"> Some content... </div> 

In your case, you probably want to add the required state to your field objects or as an immutable condition from your * ngFor.

This coursetro article has a good explanation and video too.

+4
source

Source: https://habr.com/ru/post/1266740/


All Articles