Angular Animations : How to bind animation trigger name dynamically in the template?

帅比萌擦擦* 提交于 2019-12-04 02:27:54

问题


I would like to know if there is a way to bind the animation trigger name dynamically in the template.

Here is the div to animate in the template app.component.html:

<div [@animationTriggerName]>
  ...
</div>

Here is the app.module.ts:

...
@NgModule({
  imports:      [...],
  declarations: [ ..., AnimationTriggerNameDirective ],
  bootstrap:    [...]
})

And here is the app.component.ts:

@Component({
  ...
})
export class AppComponent  {
  ...
  animationTriggerName = 'slideInOut';
}

@Directive({
  selector: '[animationTriggerName]'
})
export class AnimationTriggerNameDirective {
  @Input() animationTriggerName: string;
  constructor() {}
}

I want to be able to set the variable animationTriggerName dynamically. So if I set it to myTriggerName, then in the template I would have this rendered :

<div [@myTriggerName]>
  ...
</div>

And so the animation whose trigger name is myTriggerName would be able to run.


回答1:


after I learn from this post. it looks like use multiple states is much eaiser than using trigger name, so I change my code structure like below, below is the original post for your reference https://angularfirebase.com/lessons/hammerjs-angular-5-animations-for-mobile-gestures-tutorial/

@Component({
  selector: 'hammer-card',
  templateUrl: './hammer-card.component.html',
  styleUrls: ['./hammer-card.component.sass'],
  animations: [
    trigger('cardAnimator', [
      transition('* => wobble', animate(1000, keyframes(kf.wobble))),
      transition('* => swing', animate(1000, keyframes(kf.swing))),
      transition('* => jello', animate(1000, keyframes(kf.jello))),
      transition('* => zoomOutRight', animate(1000, keyframes(kf.zoomOutRight))),
      transition('* => slideOutLeft', animate(1000, keyframes(kf.slideOutLeft))),
      transition('* => rotateOutUpRight', animate(1000, keyframes(kf.rotateOutUpRight))),
      transition('* => flipOutY', animate(1000, keyframes(kf.flipOutY))),
    ])
  ]
})



回答2:


I have similar issues like the posted question, so far I use ngSwitch and ngSwitchCase as workaround as I fail to do the varaible binding after some try anderror. I don't think below example is the optimal solution, as it will be tedious if I want to switch the trigger name to hundred, however it works for me now, to change the trigger name in run time, hope there is some other better idea, and hope it helps

<div [ngSwitch]="child.animationName" >
 <input *ngSwitchCase="flyInOut" [@flyInOut]="'in'"  ...>
 <input *ngSwitchCase="fadeIn" [@fadeIn]="'in'"  ...> 
 <input *ngSwitchDefault [@flyRotateInOut]="'in'" ...>
</div> 


来源:https://stackoverflow.com/questions/47365594/angular-animations-how-to-bind-animation-trigger-name-dynamically-in-the-templ

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!