Skip to content

Commit

Permalink
fix: highlight term using typeahed
Browse files Browse the repository at this point in the history
fixes #591
  • Loading branch information
varnastadeus committed Jun 27, 2018
1 parent 28f2f5a commit 08f91ae
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
12 changes: 12 additions & 0 deletions src/ng-select/ng-option-highlight.directive.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@ import { By } from '@angular/platform-browser';
template: `
<span id="test1" [ngOptionHighlight]="term">My text is highlighted</span>
<span id="test2" [ngOptionHighlight]="term">My text is not highlighted</span>
<span id="test3" *ngIf="showNew" [ngOptionHighlight]="term">New label</span>
`
})
class TestComponent {
term: string;
showNew = false;
}

describe('NgOptionHighlightDirective', () => {
Expand Down Expand Up @@ -45,4 +47,14 @@ describe('NgOptionHighlightDirective', () => {
expect(span.nativeElement.querySelector('.highlighted')).toBeNull();
expect(span.nativeElement.innerHTML).toBe('My text is not highlighted');
});

it('should highlight text when label changed', () => {
fixture.componentInstance.term = 'new';
fixture.detectChanges();
fixture.componentInstance.showNew = true;
fixture.detectChanges();
const span = fixture.debugElement.query(By.css('#test3'));
expect(span.nativeElement.querySelector('.highlighted').innerHTML).toBe('New');
expect(span.nativeElement.textContent).toBe('New label');
});
});
18 changes: 12 additions & 6 deletions src/ng-select/ng-option-highlight.directive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ import {
ElementRef,
Input,
OnChanges,
Renderer2,
SimpleChanges
Renderer2
} from '@angular/core';
import { isDefined } from './value-utils';

Expand All @@ -26,17 +25,20 @@ export class NgOptionHighlightDirective implements OnChanges, AfterViewInit {
this.element = this.elementRef.nativeElement;
}

ngOnChanges(changes: SimpleChanges) {
if (isDefined(changes.term.currentValue) && isDefined(this.label)) {
this._highlightLabelWithSearchTerm();
ngOnChanges() {
if (this._canHighlight) {
this._highlightLabel();
}
}

ngAfterViewInit() {
this.label = this.element.innerHTML;
if (this._canHighlight) {
this._highlightLabel();
}
}

private _highlightLabelWithSearchTerm() {
private _highlightLabel() {
const label = this.label;
if (!this.term) {
this._setInnerHtml(label);
Expand All @@ -56,6 +58,10 @@ export class NgOptionHighlightDirective implements OnChanges, AfterViewInit {
}
}

private get _canHighlight() {
return isDefined(this.term) && isDefined(this.label);
}

private _setInnerHtml(html) {
this.renderer.setProperty(this.elementRef.nativeElement, 'innerHTML', html);
}
Expand Down

0 comments on commit 08f91ae

Please sign in to comment.