I have a simple component like this:
<div id="countdown">
<div id="countdown-number">{{ countDown }}</div>
<svg>
<circle #circle r="18" cx="20" cy="20"></circle>
</svg>
</div>
This is a circle countdown with a number in it. I have also some css, where I animate the countdown:
svg circle {
...
animation: countdown 5s linear forwards;
}
It works. Now, I want to make the 5s
variable in that way, that it is coming from the component.
For this I tried different approaches:
-
Define a property in css and modify it, f. e.:
this.renderer2.setProperty(
this.circle.nativeElement,
‘–time’,
${this.time}s
);
The initial time is showed in the component and it gets decremented, but the animation doesn’t start.
-
I set the style on the element, f. e.:
this.renderer2.setStyle(
this.circle.nativeElement,
‘animation’,
countdown ${this.time}s linear forwards
);
No luck.
The 3. option would be, that I define a simple class, which contains only the animation style, f. e.:
.start-animation {
animation: countdown 5s linear forwards;
}
And I add this to the element, f. e.:
this.renderer2.addClass(this.circle.nativeElement, 'start-animation');
This starts the animation, but the 5s
are hardcoded.
So, the question is, how to solve this issue? How can I define the animation duration dinamically?
2
Answers
I found a simpler solution. I add a variable (as above stated):
Then in the template:
Different solution using state, seems like a better approach!
Stackblitz Demo
This is my solution using angular animations, we can pass the input to angular animation the variable that holds the countdown duration inside the
params
property, Then I apply all the other static styles using a class and the dynamic property can be assigned using{{countDown}}s
, by setting the transition for:increment
and:decrement
we can restart the animation!Stackblitz Demo