Angular ng-select - All in One UI Select, Multiselect and Autocomplete library providing comprehensive select component functionality
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
The NgOptionHighlightDirective provides automatic highlighting of search terms within option text, making it easier for users to see matching content in autocomplete and search scenarios.
Highlights specified search terms within the element's text content by wrapping matches with <span class="highlighted"> elements.
/**
* Directive for highlighting search terms within option text
* Automatically escapes regex special characters and supports multiple word highlighting
*/
@Directive({
selector: '[ngOptionHighlight]'
})
export class NgOptionHighlightDirective implements OnChanges, AfterViewInit {
/** The search term to highlight within the element's text content */
@Input('ngOptionHighlight') term: string;
}Usage Examples:
import { NgOptionHighlightDirective } from '@ng-select/ng-select';
@Component({
template: `
<ng-select
[(ngModel)]="selectedCity"
[searchable]="true"
(search)="onSearch($event)">
<ng-option *ngFor="let city of filteredCities" [value]="city.id">
<span [ngOptionHighlight]="searchTerm">{{ city.name }}</span>
</ng-option>
</ng-select>
`,
imports: [NgOptionHighlightDirective]
})
export class CitySelectComponent {
searchTerm: string = '';
cities = [
{ id: 1, name: 'New York' },
{ id: 2, name: 'Los Angeles' },
{ id: 3, name: 'Chicago' }
];
filteredCities = this.cities;
onSearch(event: { term: string, items: any[] }) {
this.searchTerm = event.term;
this.filteredCities = event.items;
}
}With custom option template:
@Component({
template: `
<ng-select [(ngModel)]="selectedUser" [searchable]="true">
<ng-option *ngFor="let user of users" [value]="user.id">
<div class="user-option">
<strong [ngOptionHighlight]="searchTerm">{{ user.name }}</strong>
<small [ngOptionHighlight]="searchTerm">{{ user.email }}</small>
</div>
</ng-option>
</ng-select>
`
})
export class UserSelectComponent {
searchTerm: string = '';
users = [
{ id: 1, name: 'John Doe', email: 'john@example.com' },
{ id: 2, name: 'Jane Smith', email: 'jane@example.com' }
];
}<span class="highlighted"> for stylingThe directive wraps highlighted text with <span class="highlighted">. Add CSS to customize appearance:
.highlighted {
background-color: yellow;
font-weight: bold;
color: black;
}
/* Alternative styling */
.highlighted {
background-color: #007bff;
color: white;
padding: 1px 3px;
border-radius: 2px;
}