Blog>
Snippets

Animating Elements

Showcase how to perform simple animations on an element by altering styles over time with Renderer2.
import { Renderer2, ElementRef } from '@angular/core';

// Inject Renderer2 and ElementRef via the constructor of your component
constructor(private renderer: Renderer2, private el: ElementRef) {}

// Animate function that changes the style over time
animateElement() {
  const element = this.el.nativeElement;
  let pos = 0;
  const interval = setInterval(() => {
    if (pos === 100) { // Animation ends at position 100
      clearInterval(interval);
    } else {
      pos++;
      // Use renderer to update the style
      this.renderer.setStyle(element, 'left', pos + 'px');
    }
  }, 10); // Update every 10 milliseconds
}
This example demonstrates how to use Renderer2 to animate an element by changing its 'left' style property to move it horizontally across the screen. The 'animateElement' function creates an interval that increments the position and updates the style every 10ms, stopping when it reaches 100 pixels.