Search code examples
angularsvgsvg-animate

How to access SVG animateMotion events in Angular?


TheanimateMotion element fires three events: onbegin,onrepeat and onend. In pure Javascript I can bind an eventlistener like this:

<circle r="15" fill="red">
    <animateMotion
        dur="10s" 
        begin="indefinite" 
        repeatCount="indefinite" 
        calcMode="linear"
        repeatCount="indefinite" 
        path="...."
    />
</circle>


var anim = document.getElementsByTagName("animateMotion");

anim.onrepeat = function() {
    alert("repeat")
}
anim.onbegin = function() {
    alert("start")
}
anim.onend = function() {
    alert("end")
}

But how can I get access to these event in Angular 9? Is there any way to get access to the events?

Thx in advance, Lars


Solution

  • Try the updated approach below as my initial assumption was indeed inaccurate, since I was not too familiar with those specific events.

    Update: my initial assumption was that the below would work - was proved wrong:

    <svg:circle r="15" fill="red">
        <svg:animateMotion (repeat)="repeatMethodInsideTs()"
            dur="10s" 
            begin="indefinite" 
            repeatCount="indefinite" 
            calcMode="linear"
            repeatCount="indefinite" 
            path="...."
        />
    </svg:circle>
    

    Note in your template the XML of svg should have "svg" for each tag.

    Then I decided to still see if there are equivalent events we can just bind to in angular in a clean fashion and viola:

    <svg viewBox="0 0 200 100" xmlns="http://www.w3.org/2000/svg">
      <svg:path fill="none" stroke="lightgrey"
        d="M20,50 C20,-50 180,150 180,50 C180-50 20,150 20,50 z" />
    
      <svg:circle r="5" fill="red">
        <svg:animateMotion (beginEvent)="begin($event)" (repeatEvent)="repeat($event)" dur="3s" repeatCount="indefinite"
          path="M20,50 C20,-50 180,150 180,50 C180-50 20,150 20,50 z" />
      </svg:circle>
    </svg>
    

    Now in ts:

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent  {
      name = 'Angular';
    
      repeat(event) {
        console.log("repeat event called", event)
      }
    
      begin(event) {
        console.log("repeat event called", event)
      }
    }
    

    Here is stackblitz: https://stackblitz.com/edit/angular-px8uf3