I am trying to achieve a filter with mat-autocomplete
that is similar to the following example;
So I am trying to achieve the functionality so that when a user begins to type in the trade they are looking for filters based on a partial string match anywhere in the string and highlight this in the option.
I current have in my .html
<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>
where my .ts is
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);
}
ICategory
is a basic interface.
export interface ICategory {
value: number;
name: string;
}
And the service getCategories() just returns all the categories from an api.
The code is currently working and built per this example;
Angular Material mat-autocomplete example
I would like to add the effect of highlighting the term in the option string? Is this possible at all?