How to conditionally add animations in Angular 2

一世执手 提交于 2019-12-08 15:07:32

问题


I have a form component that has fields, some fields I want to animate when they appear in 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] doesn't seem to work.

Ideally I would like to have an animation property on my field so I could pass in animations like this [@field.Animation] but I can't find any documentation on how I would do anything like this. Any ideas?


回答1:


I've come up against a similar problem and found that you need to take a slightly different approach.

In Angular, animations are linked to state. So instead of defining a different trigger for your animation in your HTML, you want to define multiple states that your trigger can watch for in your component class. And rather than triggering animations directly from a method, you set the state of the object an animation is linked to.

So for instance I might 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 instance I'm making the animations happen as soon as the element is instantiated. And in the ngOnInit() method I'm setting this.watchMe to "fly" or "fade".

In the html I'm attaching the flyInOut trigger like so:

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

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

This article from coursetro has a nice explanation and a video too.



来源:https://stackoverflow.com/questions/43416796/how-to-conditionally-add-animations-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!