Is there a way to achieve a filter using mat-autocomplete
similar to the one shown in this example:
trade input example
I am looking to implement functionality where as users type in the trade they are searching for, filters are applied based on partial string matches anywhere in the text and these matches are highlighted in the options.
https://i.sstatic.net/5LDEK.png
This is what I currently have in my .html file:
<mat-form-field class="form-group special-input">
<input type="text" placeholder="Select a trade" aria-label="Select a trade" matInput [formControl]="categoriesCtrl" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete" md-menu-class="autocomplete">
<mat-option *ngFor="let option of filteredOptions | async" [value]="option.name">
{{ option.name }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
And here's my .ts file:
categoriesCtrl: FormControl;
filteredOptions: Observable<ICategory[]>;
options: ICategory[];
categorySubscription: Subscription;
constructor(fb: FormBuilder, private router: Router, private service: SearchService, private http: Http) {
this.categoriesCtrl = new FormControl();
}
ngOnInit() {
this.categorySubscription = this.service.getCategories().subscribe((categories: ICategory[]) => {
this.options = categories;
this.filteredOptions = this.categoriesCtrl.valueChanges
.pipe(
startWith(''),
map(options => options ? this.filter(options) : this.options.slice())
);
});
}
ngOnDestroy() {
this.categorySubscription.unsubscribe();
}
filter(val: string): ICategory[] {
return this.options.filter(x =>
x.name.toUpperCase().indexOf(val.toUpperCase()) !== -1);
}
The ICategory
interface is basic:
export interface ICategory {
value: number;
name: string;
}
The service getCategories() simply fetches all the categories from an API.
The current code functions properly and has been built following this example:
Angular Material mat-autocomplete example
Would it be possible to highlight the matching terms within the option strings? Is there a way to accomplish this?