Skip to content

Instantly share code, notes, and snippets.

@linxlad
Created June 25, 2016 22:23
Show Gist options
  • Save linxlad/76dc2ed33a7b6702d3c02146827ffbd4 to your computer and use it in GitHub Desktop.
Save linxlad/76dc2ed33a7b6702d3c02146827ffbd4 to your computer and use it in GitHub Desktop.
Auto grow directive for Angular 2.
import {Directive, ElementRef, Attribute} from 'angular2/core'
import {AnimationBuilder} from 'angular2/src/animate/animation_builder';
import {CssAnimationBuilder} from 'angular2/src/animate/css_animation_builder';
/**
* <input type="text" grow-duration="500" grow-width="400" autoGrow />
*/
@Directive({
selector: '[autoGrow]',
host: {
'(focus)': 'onFocus()',
'(blur)': 'onBlur()'
}
})
export class AutoGrowDirective {
private _animation: CssAnimationBuilder;
private startingWidth: string;
constructor(
animationBuilder:AnimationBuilder,
private el: ElementRef,
@Attribute('grow-duration') private growDuration : string,
@Attribute('grow-width') private growWidth : string
) {
this._animation = animationBuilder.css();
this.startingWidth = this.el.nativeElement.clientWidth;
// Initially start the animation so the first click will animate.
this.animate(+this.growDuration, this.startingWidth);
}
onFocus() {
this.animate(+this.growDuration, this.growWidth);
}
onBlur() {
this.animate(+this.growDuration, this.startingWidth);
}
animate(duration: number, widthInPx: string) {
let _animation = this._animation;
_animation
.setDuration(duration)
.setFromStyles({width: widthInPx + 'px'});
_animation.start(this.el.nativeElement);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment