动画 Angular2 中的参数

Parameter in to Animation Angular2

我正在尝试制作一个简单的动画,例如下面的简单 jQuery

animate({'left' : left_indent})

我正在使用 Angular2 动画,但问题是如何将组件 Class 外部的 left_indent 参数传递给动画触发器?

animations: [
    trigger('flyInOut', [

        state('for', style({
            left: this.left_indent,
        })),

        transition('* => for', [
            animate(2000, keyframes([
                style({ opacity: 1, transform: 'translateX(0)', offset: 0 }),
                style({ opacity: 1, transform: 'translateX(-300px)', offset: 0.5 }),
            ]))
        ]),
    ])
]

目前动画只允许静态定义值。

然而,根据 2016 年 6 月提出的这个 git hub feature request,有一个计划,但似乎仍积压要添加的功能。

还没有发布

我有一个解决方案。但只有当您尝试使用已知的不同参数多次使用相同的动画时,它才有用。

例如,我有可重复使用的动画来制作 slideUp-slideDown 效果。并且在折叠状态下容器必须保持一定高度(我已经知道这些容器)。

动画:

import { style, trigger, state, transition, animate } from "@angular/animations";

export const slideUpDownAnimation = (height) => {
    return trigger(`slideUpDownAnimation${height}`, [
        state('0', style({
            overflow: 'hidden',
            height: '*'
        })),
        state('1', style({
            overflow: 'hidden',
            height: `${height}px`
        })),
        transition('1 => 0', animate('400ms ease-in-out')),
        transition('0 => 1', animate('400ms ease-in-out'))
    ]);
};

在组件的class中:

import { slideUpDownAnimation } from "../../animations/slide-up-down.animation";

@Component({
    moduleId: module.id,
    selector: 'new-order',
    templateUrl: './new-order.component.html',
    animations: [
        slideUpDownAnimation(32), // will return trigger named "slideUpDownAnimation32"
        slideUpDownAnimation(60) // will return trigger named "slideUpDownAnimation60"
    ]
})
export class NewOrderComponent {...

最后,在组件的 html:

<div class="header-fields"
       [@slideUpDownAnimation32]="collapsedFields">
...

<div class="line-group"
           *ngFor="let group of lineGroups; let g = index"
           [@slideUpDownAnimation60]="group.collapsed">
...

不幸的是,它不能用于动态参数,因为您必须在装饰器中定义它们 & html。

现在有可能了。

animations: [
    trigger('flyInOut', [

        state('for', style({
            left: '{{left_indent}}', // use interpolation
        }), {params: {left_indent: 0}}), // default parameters values required

        transition('* => for', [
            animate(2000, keyframes([
                style({ opacity: 1, transform: 'translateX(0)', offset: 0 }),
                style({ opacity: 1, transform: 'translateX(-300px)', offset: 0.5 }),
            ]))
        ]),
    ])
]

更新(根据 SplitterAlex 的回答):

在模板中(对于 Angular < 4.4.6):

<div [@flyInOut]="{value: triggerValue, left_indent: left_indent}"></div>

对于 Angular >= 4.4.6 模板应该是

<div [@flyInOut]="{value: triggerValue, params: {left_indent: left_indent}}"></div>

接受的答案不适用于 Angular 4.4.6

您必须将模板中的参数值包装在一个对象中params

替换:

<div [@flyInOut]="{value: triggerValue, left_indent: left_indent}"></div>

与:

<div [@flyInOut]="{value: triggerValue, params: {left_indent: left_indent}}"></div>