-->

Angular Animations : How to bind animation trigger

2019-06-13 06:17发布

问题:

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>