Angular 2 - pass delay to component animation as i

2019-06-07 10:08发布

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?

2条回答
Melony?
2楼-- · 2019-06-07 10:16

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!

查看更多
够拽才男人
3楼-- · 2019-06-07 10:17

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 : ""))
查看更多
登录 后发表回答