将动画动态应用到 HTML 元素

Apply an animation dynamically to an HTML element

我的目的是将给定的动画应用到 html div,关于此动画名称的信息基于 [=21] 中的 Input 变量中包含的值=] 组件:

@Component({
  selector: 'test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css'],
  animations: [
    myFirstAnimation(),
    mySecondAnimation(),
    myThirdAnimation(),
  ]
})
export class TestComponent implements OnInit {
  /* 
   * The information about the name of the animation is containded in obj.animation
   * For example: obj.animation may contain '@myFirstAnimation',  '@mySecondAnimation' or '@myThirdAnimation'
   */
  @Input() obj: any;

  //...
}

如何将 obj.animation 作为 div 属性插入以便将动画动态插入 div

我尝试通过使用动画状态从不同的方法解决我的问题。

在我的 HTML 元素中,我总是引用相同的动画:

<div [@myAnimation]="obj.animation">

其中 obj.animation 可能包含不同的动画状态(例如:state1state2、...)。

动画定义如下:

trigger('myAnimation', [
  transition('void => state1', [
      style({ transform: 'translateX(-100%)', opacity: 0 }),
      animate(300, style({ transform: 'translateX(0)', opacity: 1 }))
    ]
  ),
  transition('void => state2', [
      style({ transform: 'translateX(100%)', opacity: 0 }),
      animate(300, style({ transform: 'translateX(0)', opacity: 1 }))
    ]
  ),
  //...
]);