Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

108
Visualizações
Angular 2 - How to set animations on a Directive?

I have a Directive I can put on elements that checks the current scroll position of the element in question.

Looks like this:

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

Whenever the position satifies a certain treshold, I want the element to appear on screen using an animation. I know that for a Component I can attach an animations property along with some settings in the host property to 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 a Directive?

Using: Angular 4.0.0-rc.4

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Angular 4.2 brought in a lot of animation improvements. One of them is AnimationBuilder, which allows for programmatic animation construction.

You just need to inject AnimationBuilder in your directive, and you can turn any AnimationMetadata into 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 })),
    ];
  }
}
  • Example repository
  • A New Wave of Animation Features in Angular 4.2+
about 4 years ago · Santiago Trujillo Relatório

0

I used a bit of a workaround based on this response to the issue mentioned in benshabatnoam's answer.

Directives are actually just components without templates. You can create a component that acts identical to a directive by using a attribute selector ( eg: [selector]) and making the template: <ng-content></ng-content>.

As a result, you can create a 'foux-directive' component like so:

@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 = '';
}

and use it like you would use any directive:

<div fadeInAnimation> something I want to animate </div>
about 4 years ago · Santiago Trujillo Relatório

0

As I mentioned in your question's comment section.

You can have the animation configuration in your parent component. Then the directive just adds a class on its host when it satisfies the threshold.

In your directive, you can have something like:

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

// when logic is true
this.animationTrigger = this.classThatTriggersAnimation;
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda