我正在玩动画API,我想为顶级路由视图创建一个可重用的动画,比如滑入内容.我成功地通过了时髦的元数据语法(一旦克服了使用元数据的疯狂 idea ,它实际上相当酷)来让动画大部分工作正常.

   @Component({
      //moduleId: module.id,
      selector: 'album-display',
      templateUrl: './albumDisplay.html',
      animations: [
        trigger('slideIn', [
          state('*', style({
            transform: 'translateX(100%)',
          })),
          state('in', style({
            transform: 'translateX(0)',
          })),
          state('out',   style({
            transform: 'translateX(-100%)',
          })),
          transition('* => in', animate('600ms ease-in')),
          transition('in => out', animate('600ms ease-in'))
        ])
      ]
  })
  export class AlbumDisplay implements OnInit {
      slideInState = 'in';
      ...
  }

然后将其分配给组件中的顶级元素:

  <div  class="container" [@slideIn]="slideInState">

这是可行的,但我怎样才能使其可重复使用?我不想把这些元数据粘贴到每个视图上.因为这是元数据,所以我不确定如何使其可重用.

推荐答案

一种可能的方法是将动画触发器代码放在单独的文件中,并将其导出为const变量,然后在组件中使用,如下所示.

animations.ts

import { trigger, state, style, transition, animate } from '@angular/core';

export const slideIn = trigger('slideIn', [
  state('*', style({
    transform: 'translateX(100%)',
  })),
  state('in', style({
    transform: 'translateX(0)',
  })),
  state('out',   style({
    transform: 'translateX(-100%)',
  })),
  transition('* => in', animate('600ms ease-in')),
  transition('in => out', animate('600ms ease-in'))
]);

album-display.component.ts

import { slideIn } from './animations'; // path to your animations.ts file

@Component({
    //moduleId: module.id,
    selector: 'album-display',
    templateUrl: './albumDisplay.html',
    animations: [
      slideIn
    ]
})
export class AlbumDisplay implements OnInit {
    slideInState = 'in';
    ...
}

Angular相关问答推荐

如何使用ChangeDetectionStrategy.OnPush?

在Drective Composure API中使用指令输出

Angular 17:延迟加载带参数的独立组件?

VS代码中带Angular 17的缩进新控制流

出错后可观察到的重用

使用 Electron 打包器打包 Electron Angular 应用程序时无法加载资源

IonicStorageModule似乎不是 NgModule 类

如何在 Angular14 中创建带有验证的自定义输入组件?

以 Angular 形式添加动态控件失败

Angular 等待对话框未显示

Angular:为什么在我的自定义 ErrorHandler 中订阅主题不触发?

如何在本地处理错误并跳过 Angular HTTP 拦截器?

Angular 2 二传手与 ngOnChanges

不再需要 core-js 了吗?

在同一个组件中使用 MatSort 的多个 mat-table

ConnectionBackend 没有提供程序

从 angular2 模板调用静态函数

无法绑定到 target,因为它不是div的已知属性

路由 getCurrentNavigation 始终返回 null

获取对组件中使用的指令的引用