Skip to content

Instantly share code, notes, and snippets.

@gorango
Created September 26, 2016 23:53
Show Gist options
  • Save gorango/ee6cd74884529fd0477a1ec9a3b82eae to your computer and use it in GitHub Desktop.
Save gorango/ee6cd74884529fd0477a1ec9a3b82eae to your computer and use it in GitHub Desktop.
import {AfterViewInit, Directive, ElementRef, Input, Renderer} from '@angular/core';
/**
* ng2 FitText directive.
*/
@Directive({
selector: '[fitText]'
})
export class FitText implements AfterViewInit {
private factor: number;
private element: HTMLElement;
private active: boolean;
private settings: any;
private options: any;
private defaults = {
minFontSize: -1 / 0,
maxFontSize: 1 / 0,
active: true,
startSize: 0
}
@Input() set fitFactor(factor: number) { this.factor = factor; }
@Input() set fitOptions(options: any) { this.options = options; }
constructor(private el: ElementRef, private render: Renderer) {
this.element = this.el.nativeElement;
this.active = true;
this.settings = this.options ? Object.assign(this.defaults, this.options) : this.defaults;
}
ngAfterViewInit() {
if (this.settings.active) {
this.activate();
}
}
getMinWidth() {
return this.element.getAttribute('data-minwidth');
}
doresize() {
let fontSize =
Math.max(
Math.min(
this.element.clientWidth / (this.factor * 10),
parseFloat(this.settings.maxFontSize)
),
parseFloat(this.settings.minFontSize)
) + 'px';
this.element.style.fontSize = fontSize;
}
conditionalresize() {
if (window.innerWidth > this.settings.minwidth) {
let fontSize =
Math.max(
Math.min(
this.element.clientWidth / (this.factor * 10),
parseFloat(this.settings.maxFontSize)
),
parseFloat(this.settings.minFontSize)
) + 'px';
this.element.style.fontSize = fontSize;
} else {
this.element.style.fontSize = '';
}
}
activate() {
if (this.settings.minwidth) {
window.addEventListener('resize', this.conditionalresize.bind(this));
this.conditionalresize();
} else {
window.addEventListener('resize', this.doresize.bind(this));
this.doresize();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment