ref: Created a dedicated method to determine if the element has overflow or not

This commit is contained in:
Giacomo Ferlaino 2020-03-18 02:00:36 +01:00
parent 0de40db2b6
commit 0cd17ab15b
2 changed files with 49 additions and 7 deletions

View file

@ -109,13 +109,7 @@ export class Ng2FittextDirective
ngAfterViewInit() { ngAfterViewInit() {
if (this.isVisible() && !this.isDone()) { if (this.isVisible() && !this.isDone()) {
if (this.fittext) { if (this.fittext) {
const overflow = this.container if (this.hasOverflow()) {
? this.checkOverflow(this.container, this.el.nativeElement)
: this.checkOverflow(
this.el.nativeElement.parentElement,
this.el.nativeElement
);
if (overflow) {
if (this.fontSize > this.minFontSize) { if (this.fontSize > this.minFontSize) {
// iterate only until font size is bigger than minimal value // iterate only until font size is bigger than minimal value
this.setFontSize(this.calculateFontSize(this.fontSize, this.speed)); this.setFontSize(this.calculateFontSize(this.fontSize, this.speed));
@ -165,4 +159,13 @@ export class Ng2FittextDirective
isVisible(): boolean { isVisible(): boolean {
return this.getStartFontSizeFromHeight() > 0; return this.getStartFontSizeFromHeight() > 0;
} }
hasOverflow(): boolean {
return this.container
? this.checkOverflow(this.container, this.el.nativeElement)
: this.checkOverflow(
this.el.nativeElement.parentElement,
this.el.nativeElement
);
}
} }

View file

@ -268,4 +268,43 @@ describe('Class: Ng2FittextDirective', () => {
).toBe(true); ).toBe(true);
}); });
}); });
describe('Method: hasOverflow', () => {
let containerMock: any;
let parentElementMock: any;
beforeEach(() => {
containerMock = {
isContainer: true,
};
parentElementMock = {
isParentElement: true,
};
ng2FittextDirective.container = { ...containerMock };
ng2FittextDirective.el.nativeElement = {
parentElement: { ...parentElementMock },
} as HTMLElement;
});
it('Should calculate the overflow using the container if is present', () => {
spyOn(ng2FittextDirective, 'checkOverflow').and.callFake(
(parentElement: any, childrenElement: any) => {
expect(parentElement).toEqual(containerMock);
return true;
}
);
expect(ng2FittextDirective.hasOverflow()).toBe(true);
});
it('Should calculate the overflow using the parent element if the container is not present', () => {
delete ng2FittextDirective.container;
spyOn(ng2FittextDirective, 'checkOverflow').and.callFake(
(parentElement: any, childrenElement: any) => {
expect(parentElement).toEqual(parentElementMock);
return true;
}
);
expect(ng2FittextDirective.hasOverflow()).toBe(true);
});
});
}); });