如何在 angular 中动态设置状态数

how to dynamically set the number of states in angular

  changeDetection: ChangeDetectionStrategy.OnPush,
  animations: [
    trigger('slide', [
      state('1', style({ transform: 'translateX(0)' })),
      state('2', style({ transform: 'translateX(-50%)' })),
      transition('* => *', animate(300))
    ])
  ]
})

export class SlidePanelComponent {
  @Input() numberOfStatesToHave

... more code

如何使用 @input 装饰器动态设置 angular 中的状态数?

例如,如果@Input numberOfStatesToHave 为 3,我如何才能在 @Component 装饰器的动画 'array' 中拥有三个动画状态?并且还动态地将值传递给转换 css 属性?

我认为这是不可能的。但我对您的要求的建议如下。

const numberOfStatesToHave = localStorage.getItem('NUMBEROFSTATESTOHAVE')

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
    changeDetection: ChangeDetectionStrategy.OnPush,
    animations: [
      trigger('slide', numberOfStatesToHave)
    ]
})

如果在调用此组件之前设置 localStorage

经过研究(感谢@SplitterAlex 的评论为我指明了正确的方向),我想出了一个解决方案。

要动态创建动画状态,您应该在 @Components 装饰器中使用动画逻辑,但您应该使用 angular 的 Animationbuilder.

这个 stackblitz example 帮助我理解了动画生成器的工作原理,因为它将它与在 @Component 装饰器中制作动画进行了对比。

Here is my complete code动态设置动画状态数angular.