Answer the question
In order to leave comments, you need to log in
How to dynamically set animation speed in Angular 2?
I'm using TypeScript and Angular 2.4
I have a directive to scroll long text (something like a marquee tag).
It takes a "speed" parameter which describes the scrolling speed (pixels per second).
This allows you to maintain the same speed for any length of text.
Angular 2 has the ability to describe the animation in the @Component decorator, but you can't refer to the component's methods.
In order to convert it to normal speed in seconds, I need to know the length of the element itself.
Component code:
import {Component, Input, ElementRef, trigger, state, style, transition, animate} from '@angular/core';
import * as $ from 'jquery';
const SCROLL_SPEED_DEFAULT = 25;
@Component({
selector: 'text-scroll',
template: '<span><ng-content></ng-content></span>',
animations: [
trigger('hover', [
state('idle', style({transformX: '0'})),
state('scrolled', style({transformX: '-100%'})),
transition('idle => scrolled', [
animate(this.getAnimationSpeed())
])
])
]
})
export class TextScrollComponent {
@Input('speed') speedTime: number = SCROLL_SPEED_DEFAULT;
private element: HTMLElement;
constructor(private el: ElementRef) {
this.element = this.el.nativeElement;
}
public getAnimationSpeed(): number {
let element = this.element;
let elementWidth = $(element).width();
let difference = this.el.nativeElement.scrollWidth - elementWidth;
return (difference / Number(this.speedTime)) * 1000;
}
}
<text-scroll>My very <b>loooong..</b> text</text-scroll>
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question