How to add a search filter to a select option in angular
If you want to filter in select option, you can use datalist control of HTML. If you use it, there is no need to do extra coding for filtering. It has built-in functionality for filtering.
HTML :
<input list="menace" name="menace">
<datalist id="menace">
<option *ngFor="let menace of menaces">{{menace.nom}} </option>
</datalist>
I think you can use ng-select: https://www.npmjs.com/package/@ng-select/ng-select for Yor Requirement
If you want to filter your array menaces
by typing on the first letter, then it is possible to filter your array like this:
HTML:
<select class="form-control"
(change)="mnVuln?.menaceActif?.menace.id = $event.target.value;
updateMenaceProcessus();
filterMenaces($event)">
<option></option>
<option *ngFor="let menace of menaces"
[value]="menace.id"
[selected]="menace.id === mnVuln?.menaceActif?.menace.id">
{{menace.nom}}</option>
</select>
TypeScript:
origMenaces = [];
methodAPIToGetMenaces() {
this.yourService()
.subscribe(s=> {
this.menaces = s;
this.origMenaces = s;
});
}
filterMenaces(str: string) {
if (typeof str === 'string') {
this.menaces = this.origMenaces.filter(a => a.toLowerCase()
.startsWith(str.toLowerCase()));
}
}
UPDATE 1:
If you want to filter by input
value:
HTML:
<input type="text"
(ngModelChange)="filterItem($event)"
[(ngModel)]="filterText">
<br>
<select
#selectList
[(ngModel)]="myDropDown"
(ngModelChange)="onChangeofOptions($event)">
<option value="empty"></option>
<option *ngFor="let item of items">
{{item}}
</option>
</select>
<p>items {{ items | json }}</p>
TypeScript:
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular 4';
myDropDown : string;
items = ['one', 'two', 'three'];
origItems = ['one', 'two', 'three'];
@ViewChild('selectList', { static: false }) selectList: ElementRef;
onChangeofOptions(newGov) {
console.log(newGov);
}
filterItem(event){
if(!event){
this.items = this.origItems;
} // when nothing has typed*/
if (typeof event === 'string') {
console.log(event);
this.items = this.origItems.filter(a => a.toLowerCase()
.startsWith(event.toLowerCase()));
}
console.log(this.items.length);
this.selectList.nativeElement.size = this.items.length + 1 ;
}
}
Please, see work example at stackblitz