@ng-select/ng-option-highlight
Version:
```shell npm install --save @ng-select/ng-option-highlight ```
72 lines (66 loc) • 3.28 kB
JavaScript
import * as i0 from '@angular/core';
import { inject, ElementRef, Renderer2, signal, input, computed, effect, afterNextRender, Directive } from '@angular/core';
function isDefined(value) {
return value !== undefined && value !== null;
}
function escapeRegExp(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
class NgOptionHighlightDirective {
constructor() {
// Dependencies
this.element = inject((ElementRef)).nativeElement;
this.renderer = inject(Renderer2);
// Signals
this.label = signal('', /* @ts-ignore */
...(ngDevMode ? [{ debugName: "label" }] : /* istanbul ignore next */ []));
// Inputs
this.term = input('', { ...(ngDevMode ? { debugName: "term" } : /* istanbul ignore next */ {}), alias: 'ngOptionHighlight' });
// Computed properties
this.canHighlight = computed(() => isDefined(this.term()) && isDefined(this.label()) && this.label() !== '', /* @ts-ignore */
...(ngDevMode ? [{ debugName: "canHighlight" }] : /* istanbul ignore next */ []));
// Update innerHTML using effect
this._effectUpdateInnerHtml = effect(() => {
if (!this.canHighlight()) {
return;
}
this._highlightLabel();
}, /* @ts-ignore */
...(ngDevMode ? [{ debugName: "_effectUpdateInnerHtml" }] : /* istanbul ignore next */ []));
this._ = afterNextRender(() => {
this.label.set(this.element.innerHTML);
// 1st label highlight triggers from here
this._highlightLabel();
});
}
_highlightLabel() {
const label = this.label();
if (!this.term()) {
this._setInnerHtml(label);
return;
}
const alternationString = escapeRegExp(this.term()).replace(' ', '|');
const termRegex = new RegExp(alternationString, 'gi');
this._setInnerHtml(label.replace(termRegex, `<span class=\"highlighted\">$&</span>`));
}
_setInnerHtml(html) {
this.renderer.setProperty(this.element, 'innerHTML', html);
}
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.4", ngImport: i0, type: NgOptionHighlightDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive }); }
static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "22.0.4", type: NgOptionHighlightDirective, isStandalone: true, selector: "[ngOptionHighlight]", inputs: { term: { classPropertyName: "term", publicName: "ngOptionHighlight", isSignal: true, isRequired: false, transformFunction: null } }, ngImport: i0 }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.4", ngImport: i0, type: NgOptionHighlightDirective, decorators: [{
type: Directive,
args: [{
selector: '[ngOptionHighlight]',
standalone: true,
}]
}], propDecorators: { term: [{ type: i0.Input, args: [{ isSignal: true, alias: "ngOptionHighlight", required: false }] }] } });
/*
* Public API Surface of ng-option-highlight
*/
/**
* Generated bundle index. Do not edit.
*/
export { NgOptionHighlightDirective };
//# sourceMappingURL=ng-select-ng-option-highlight.mjs.map