Dynamic Animation Parameters with Angular Directives
Dynamically change animation parameters such as duration, delay, and easing by binding properties in a custom directive to control Angular animations.
import { Directive, Input, ElementRef, Renderer2, OnInit } from '@angular/core';
import { AnimationBuilder, style, animate } from '@angular/animations';
@Directive({
selector: '[appDynamicAnimation]'
})
export class DynamicAnimationDirective implements OnInit {
@Input() duration: number = 300; // Default duration in milliseconds
@Input() delay: number = 0; // Default delay in milliseconds
@Input() easing: string = 'linear'; // Default easing function
constructor(private el: ElementRef, private renderer: Renderer2, private builder: AnimationBuilder) { }
ngOnInit() {
this.animateElement();
}
private animateElement() {
// Create the animation
const animation = this.builder.build([
style({ transform: 'scale(1)' }),
animate(`${this.duration}ms ${this.delay}ms ${this.easing}`, style({ transform: 'scale(1.5)' }))
]);
// Apply the animation to the element
const player = animation.create(this.el.nativeElement);
player.play();
}
}
This Angular directive, appDynamicAnimation, allows you to bind custom duration, delay, and easing properties to an element's scale animation. The AnimationBuilder is used to build the animation sequence with the given parameters, and OnInit ensures the animation initializes when the directive is applied to an element.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { DynamicAnimationDirective } from './dynamic-animation.directive';
@NgModule({
declarations: [
AppComponent,
DynamicAnimationDirective // Declare the directive
],
imports: [
BrowserModule,
BrowserAnimationsModule // Import BrowserAnimationsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
This snippet includes the AppModule for Angular where the BrowserAnimationsModule is imported and the custom DynamicAnimationDirective is declared. This module sets up the environment needed for the animations to work within the Angular application.
<div [appDynamicAnimation]="{ duration: 200, delay: 100, easing: 'ease-out' }" >Animate me</div>
This is an example usage of the appDynamicAnimation directive in an Angular template. You bind an object with custom animation properties (duration, delay, easing) to the directive to control the parameters of the animation.