本文介绍了如何在Angular 2中有条件地添加动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含字段的表单组件,有些字段要在表单中显示时要设置动画,但不是每个字段。

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>

使用其他属性,我可以执行以下操作: [attr.required] = field.Required 但是 [attr。@ slideOut] 似乎不起作用。

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

理想情况下,我想在我的字段上设置一个动画属性,以便可以传递这样的动画,例如 [@ field.Animation] ,但我找不到任何动画有关如何进行此类操作的文档。有任何想法吗?

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?

推荐答案

我遇到了类似的问题,发现您需要采取略有不同的方法。

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

在Angular中,动画链接到状态。因此,您不想在HTML中为动画定义其他触发器,而是要定义触发器可以在组件类中监视的多个状态。而不是直接从方法中触发动画,而是设置动画链接到的对象的状态。

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})
          ]))
        ]
      )
    ])
  ]
})

在这种情况下,我会尽快制作动画元素被实例化。然后在ngOnInit()方法中,将this.watchMe设置为 fly或 fade。

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".

在html中,我将flyInOut触发器附加为这样:

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

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

在您的情况下,您可能想将所需的状态添加到字段对象中,或者将其作为可迭代的条件您的* ngFor。

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.

这篇关于如何在Angular 2中有条件地添加动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 06:28
查看更多