diff --git a/src/ng2fittext.directive.ts b/src/ng2fittext.directive.ts index b4076bd..3f53ee2 100644 --- a/src/ng2fittext.directive.ts +++ b/src/ng2fittext.directive.ts @@ -1,44 +1,55 @@ -import {Directive, ElementRef, Renderer, Input, AfterViewInit, HostListener} from '@angular/core'; +import {Directive, ElementRef, Renderer, Input, AfterViewInit, HostListener, OnInit} from '@angular/core'; @Directive({ selector: '[fittext]' }) -export class Ng2FittextDirective implements AfterViewInit { +export class Ng2FittextDirective implements AfterViewInit, OnInit { @Input('fittext') fittext: any; @Input('container') container: any; @Input('activateOnResize') activateOnResize: boolean; - public fontSize:number = 0; - public speed:number = 1.05; + private fontSize: number = 0; + private speed: number = 1.05; constructor(public el: ElementRef, public renderer: Renderer) { } + + setFontSize(fontSize) { + this.fontSize = fontSize; + return this.el.nativeElement.style.setProperty('font-size', (fontSize).toString()+'px'); + } + + calculateFontSize(fontSize, speed){ + // TODO Do with Gauss + return Math.floor(fontSize/speed); + } checkOverflow(parent:any, children:any) { - return (children.clientHeight > parent.clientHeight || children.scrollWidth > parent.clientWidth); + let overflowX = children.scrollWidth - parent.clientWidth; + let overflowY = children.clientHeight - parent.clientHeight; + return (overflowX > 1 || overflowY > 1); } @HostListener('window:resize', ['$event']) onResize() { - if(this.activateOnResize){ - this.fontSize = 0; + if(this.activateOnResize && this.fittext) { + this.setFontSize(this.container.clientWidth); this.ngAfterViewInit(); } } + ngOnInit() { + if (this.fittext) { + this.setFontSize(this.container.clientWidth); + this.el.nativeElement.style.setProperty('will-change', 'content'); + } + } + ngAfterViewInit() { if (this.fittext) { - if(this.fontSize == 0){ - this.fontSize = this.container.clientWidth; - this.el.nativeElement.style.setProperty('font-size', (this.fontSize).toString()+'px'); - } let overflow = this.checkOverflow(this.container, this.el.nativeElement); if(overflow) { - if(this.fontSize < 2) { - return; - } - this.fontSize = Math.floor(this.fontSize/this.speed); - this.el.nativeElement.style.setProperty('font-size', (this.fontSize).toString()+'px'); + this.setFontSize(this.calculateFontSize(this.fontSize, this.speed)); this.ngAfterViewInit(); } }