Skip to content

Commit

Permalink
fix(tooltip): implement change detection
Browse files Browse the repository at this point in the history
This fixes issues with custom tooltip class changes  not being applied after
tooltip creation.

Fixes: ng-bootstrap#3335
  • Loading branch information
peterblazejewicz committed Sep 24, 2019
1 parent 0186404 commit a863e22
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
12 changes: 12 additions & 0 deletions src/tooltip/tooltip.spec.ts
Expand Up @@ -60,6 +60,18 @@ describe('ngb-tooltip-window', () => {
expect(fixture.nativeElement).toHaveCssClass('my-custom-class');
});

it('should allow to change custom class to new one', () => {
const fixture = TestBed.createComponent(NgbTooltipWindow);
fixture.componentInstance.tooltipClass = 'first-custom-class';
fixture.detectChanges();
fixture.componentInstance.tooltipClass = 'second-custom-class';
fixture.detectChanges();
fixture.componentInstance.tooltipClass = 'third-custom-class';
fixture.detectChanges();

expect(fixture.nativeElement).toHaveCssClass('third-custom-class');
});

});

describe('ngb-tooltip', () => {
Expand Down
26 changes: 23 additions & 3 deletions src/tooltip/tooltip.ts
Expand Up @@ -18,7 +18,9 @@ import {
NgZone,
ViewEncapsulation,
ChangeDetectorRef,
ApplicationRef
ApplicationRef,
OnChanges,
SimpleChanges
} from '@angular/core';
import {DOCUMENT} from '@angular/common';

Expand All @@ -39,16 +41,27 @@ let nextId = 0;
template: `<div class="arrow"></div><div class="tooltip-inner"><ng-content></ng-content></div>`,
styleUrls: ['./tooltip.scss']
})
export class NgbTooltipWindow {
export class NgbTooltipWindow implements OnChanges {

@Input() id: string;
@Input() tooltipClass: string;

constructor(private _changeDetector: ChangeDetectorRef) {}

ngOnChanges(changes: SimpleChanges): void {
const tooltipClassChange = changes['tooltipClass'];
if (tooltipClassChange && !tooltipClassChange.firstChange) {
this._changeDetector.markForCheck();
}
}
}

/**
* A lightweight and extensible directive for fancy tooltip creation.
*/
@Directive({selector: '[ngbTooltip]', exportAs: 'ngbTooltip'})
export class NgbTooltip implements OnInit, OnDestroy {
export class NgbTooltip implements OnInit, OnDestroy, OnChanges {

/**
* Indicates whether the tooltip should be closed on `Escape` key and inside/outside clicks:
*
Expand Down Expand Up @@ -253,6 +266,13 @@ export class NgbTooltip implements OnInit, OnDestroy {
this.close.bind(this), +this.openDelay, +this.closeDelay);
}

ngOnChanges(changes: SimpleChanges) {
const tooltipClassChange = changes['tooltipClass'];
if (tooltipClassChange && !tooltipClassChange.firstChange && this._windowRef) {
this._windowRef.instance.tooltipClass = tooltipClassChange.currentValue;
}
}

ngOnDestroy() {
this.close();
// This check is needed as it might happen that ngOnDestroy is called before ngOnInit
Expand Down

0 comments on commit a863e22

Please sign in to comment.