首页 > 解决方案 > 如何在Angular中有条件地设置动画:进入和:离开过渡?

问题描述

我有一个列表,其中的项目有这样的动画:

<li @animation>

这是我的动画触发器:

trigger('animation', [
  transition(':enter', [
    style({ height: '0px', 'padding-top': '0', 'padding-bottom': '0'}),  // initial
    animate('0.5s',
      style({ height: '*', 'padding-top': '*', 'padding-bottom': '*'}))  // final
  ]),
  transition(':leave', [
    style({ height: '*', 'padding-top': '*', 'padding-bottom': '*', opacity: 1}),  // initial
    animate('0.5s',
      style({ height: '0px', 'padding-top': '0', 'padding-bottom': '0', opacity: 0}))  // final
  ])
])

如何有条件地为特定项目打开/关闭此动画?其实我在找某事。像这样:

<li [@animation]=item.isAnimated>

这根本不起作用。

不幸的是,Angular 文档中只有一句话:

对于进入或离开页面的元素(插入或从 DOM 中删除),您可以使动画有条件。例如,将 *ngIf 与 HTML 模板中的动画触发器一起使用。

但是当我将动画注释与 *ngIf 结合使用时,显然根本不会显示非动画项目:

<li *ngIf="item.isAnimated" @animation>

无论 isAnimated 标志如何,我都想进一步显示所有项目。我只想打开/关闭特定项目的动画。

标签: angularangular-animations

解决方案


根据Angular IO

当为 true 时,特殊的动画控件绑定 @.disabled 绑定会阻止所有动画的渲染。将 @.disabled 绑定放在元素上以禁用元素本身的动画,以及元素内的任何内部动画触发器。

以下示例显示了如何使用此功能:

@Component({
    selector: 'my-component',
    template: `
    <div [@.disabled]="isDisabled">
        <div [@childAnimation]="exp"></div>
    </div>
    `,
    animations: [
        trigger("childAnimation", [
            // ...
        ])
    ]
})
class MyComponent {
      isDisabled = true;
  exp = '...';
}

当 @.disabled 为 true 时,它​​会阻止 @childAnimation 触发器以及任何内部动画进行动画处理。


推荐阅读