Angular 2 - How to set up animation in a directive?

I have. DirectiveI can put on elements that check the current scroll position of the corresponding element.

It looks like:

@Directive({
    selector: '[my-scroll-animation]'
})

Whenever a position suits a certain trident, I want the element to be displayed on the screen using animation. I know that for ComponentI can add a property animationsalong with some settings in the property hostto activate the animation.

I would like something like this:

import { myScrollAnimation } from './animations';

@Directive({
    selector: '[my-scroll-animation]'
    animations: [myScrollAnimation] // <- not possible?
})

How can I achieve this in the Directive?

Usage: Angular 4.0.0-rc.4

+4
source share
4 answers

As I mentioned in the comments section of the question.

. , .

- :

@Input() classThatTriggersAnimation = "do-animation";
@HostBinding('[@nameOfAnimation]') animationTrigger = ""; 

// when logic is true
this.animationTrigger = this.classThatTriggersAnimation;
+2

( - 28/08/17) angular git. , , , .

+2

, , benshabatnoam .

. , , (: [selector]) : <ng-content></ng-content>.

'foux-directive' :

@Component({
    selector: '[fadeInAnimation]',
    animations: [
        trigger('fadeIn', [
             transition(':enter', [
                 style({opacity:'0'}),
                 animate(200, style({opacity:'1'}))
             ])
        ])
    ], 
    template: `<ng-content></ng-content>`,
})
export class FadeInDirective {
    @HostBinding('@fadeIn') trigger = '';
}

, :

<div fadeInAnimation> something I want to animate </div>
0
source

Angular 4.2 has brought many animation improvements. One of them is AnimationBuilder, which allows you to create software animations.

You just need to introduce AnimationBuilder into your directive, and you can turn any AnimationMetadata into a working animation.

@Directive({
  selector: '[zetFadeInOut]',
})
export class FadeInOutDirective {
  player: AnimationPlayer;

  @Input()
  set show(show: boolean) {
    if (this.player) {
      this.player.destroy();
    }

    const metadata = show ? this.fadeIn() : this.fadeOut();

    const factory = this.builder.build(metadata);
    const player = factory.create(this.el.nativeElement);

    player.play();
  }

  constructor(private builder: AnimationBuilder, private el: ElementRef) {}

  private fadeIn(): AnimationMetadata[] {
    return [
      style({ opacity: 0 }),
      animate('400ms ease-in', style({ opacity: 1 })),
    ];
  }

  private fadeOut(): AnimationMetadata[] {
    return [
      style({ opacity: '*' }),
      animate('400ms ease-in', style({ opacity: 0 })),
    ];
  }
}
0
source

Source: https://habr.com/ru/post/1672643/


All Articles