Creating a reusable animation directive

So far, we have seen how we can create an AnimationBuilder and how we can use it to programmatically create and apply animations at will. One way of making it reusable is to wrap it inside a directive. Creating a directive is quite a simple feat that we have done a few times already; the thing we need to keep in mind is that our directive will be applied to an element and this element is the thing that will be animated by our animation. Let's summarize what we need to do in a list:

  1. Create a directive.
  2. Inject AnimationBuilder.
  3. Create our animation.
  4. Create an animation player.
  5. Play the animation.

This list of things is very similar to when we explained how the AnimationBuilder worked, and it should be; after all, the directive is the only new thing here. Let's define our directive and the animation; there really isn't much to it:

@Directive({
selector : '[highlight]'
})
export class HighlightDirective implements OnInit {
constructor(
private elementRef: ElementRef,
private animationBuilder: AnimationBuilder
) {}

ngOnInit() {
const animation = this.animationBuilder.build([
style({ width: '0px' }),
animate(1000, style({ width : '100px' }))
]);
const player = animation.create( this.elementRef.nativeElement );
player.play();
}
}

This is all we need. Now we can just apply our directive to any element, like so:

<p highlight>animate me</p>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset