Angular 可复用动画

可复用动画

本主题提供了一些关于如何创建可复用动画的例子。

前提条件

在继续本主题前,你需要熟悉下列知识:

创建可复用动画

要想创建可复用的动画,请使用 ​animation()​ 方法来在独立的 ​.ts​ 文件中定义动画,并把该动画的定义声明为一个导出的 ​const ​变量。然后你就可以在应用的组件代码中通过 ​useAnimation()​ 来导入并复用它了。

import { animation, style, animate, trigger, transition, useAnimation } from @angular/animations;

export const transitionAnimation = animation([
  style({
    height: {{ height }},
    opacity: {{ opacity }},
    backgroundColor: {{ backgroundColor }}
  }),
  animate({{ time }})
]);

在上面的代码片段中,通过把 ​transitionAnimation ​声明为一个导出的变量,就让它变成了可复用的。

注意:
height​、​opacity​、​backgroundColor ​和 ​time ​这几个输入项会在运行期间被替换掉。

你还可以导出某个动画的一部分。比如,下列代码片段会导出 ​trigger ​这个动画。

import { animation, style, animate, trigger, transition, useAnimation } from @angular/animations;
export const triggerAnimation = trigger(openClose, [
  transition(open => closed, [
    useAnimation(transitionAnimation, {
      params: {
        height: 0,
        opacity: 1,
        backgroundColor: red,
        time: 1s
      }
    })
  ])
]);

从现在起,你可以在组件类中导入这些可复用动画变量。比如下面的代码片段就导入了 ​transitionAnimation ​变量,并通过 ​useAnimation()​ 函数来复用它。

import { Component } from @angular/core;
import { transition, trigger, useAnimation } from @angular/animations;
import { transitionAnimation } from ./animations;

@Component({
  selector: app-open-close-reusable,
  animations: [
    trigger(openClose, [
      transition(open => closed, [
        useAnimation(transitionAnimation, {
          params: {
            height: 0,
            opacity: 1,
            backgroundColor: red,
            time: 1s
          }
        })
      ])
    ])
  ],
  templateUrl: open-close.component.html,
  styleUrls: [open-close.component.css]
})

作者:唐伯虎点蚊香,如若转载,请注明出处:https://www.web176.com/angular13/24092.html

(0)
打赏 支付宝 支付宝 微信 微信
唐伯虎点蚊香的头像唐伯虎点蚊香
上一篇 2023年6月18日
下一篇 2023年6月18日

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注