Angular 2 - pass delay to component animation as input parameter

心不动则不痛 提交于 2019-12-08 05:55:33

问题


I want to pass in the delay of a component's animation from the html eg:

html:

<circles[delay]="'10000ms'"></circles> 

ts:

@Component({
   selector: 'circles',
   templateUrl: 'app/landing-page/subcomponents/circles.component.html',
   styleUrls: ['app/landing-page/subcomponents/circles.component.css'],
    animations: [
        trigger('flyIn', [
            state('in', style({ transform: 'translateY(0)', opacity: 1 })),
            transition('void => *', [
                style({ transform: 'translateY(-100%)', opacity: 0 }),
                animate("1000ms" + this.delay)
            ])
        ])
    ]
})

export class CirclesComponent {
   @Input() private delay: string; 

However when I do that it gives this error:

(SystemJS) Cannot read property 'delay' of undefined(…)

How can I pass in the delay to the component in html without causing this error?


回答1:


You are trying to use this in this.delay to refer to the current class, but you are doing this outside the class. Note that @Component() function is executed before you declare class CirclesComponent

This isn't very elegant but you could set a property on the window object when you want to set the delay

window.custom = {delay:'1000ms'}

Then in your animation, you could access it with `window.custom? window.custom.delay :

animate("1000ms" + (window.custom? window.custom.delay : ""))



回答2:


I might be a little bit late but this may help someone else.

// Define your animations
export const fadeInDelay =
  trigger('fadeInDelay', [
    transition('void => *', [
        style({ opacity: '0' }),
        animate('250ms {{delay}}ms ease-in')
      ],
      { params: { delay: 200 } } //Fallback value; else it could crash when no delay is passed
    )
  ]);

Load it into your component:

@Component({
  animations: [fadeInDelay]
})
export class Component {
  ...
}

Then you can use it in your template like this and control the delay for each animation:

<div [@fadeInDelay]="{value: '', params: { delay: 1000}}"></div>
<div [@fadeInDelay]="{value: '', params: { delay: 2000}}"></div>
<div [@fadeInDelay]></div> //using fallback

Don´t forget to pass the a value else it will not work. I hope this helps!



来源:https://stackoverflow.com/questions/40145581/angular-2-pass-delay-to-component-animation-as-input-parameter

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