垫自动完成过滤器以突出显示部分字符串匹配 [英] mat-autocomplete filter to hightlight partial string matches
问题描述
我正在尝试使用mat-autocomplete
实现类似于以下示例的过滤器;
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.
我当前在.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>
我的.ts在哪里
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
是基本接口.
export interface ICategory {
value: number;
name: string;
}
服务getCategories()只是从api返回所有类别.
And the service getCategories() just returns all the categories from an api.
此示例当前正在使用和构建代码;
The code is currently working and built per this example;
我想在选项字符串中添加突出显示该术语的效果吗?这有可能吗?
I would like to add the effect of highlighting the term in the option string? Is this possible at all?
推荐答案
只要用户在过滤器中输入内容,就可以使用自定义管道突出显示部分匹配项.
You can use a custom pipe to highlight the partial match whenever the user types in something in the filter.
@Pipe({ name: 'highlight' })
export class HighlightPipe implements PipeTransform {
transform(text: string, search): string {
const pattern = search
.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&")
.split(' ')
.filter(t => t.length > 0)
.join('|');
const regex = new RegExp(pattern, 'gi');
return search ? text.replace(regex, match => `<b>${match}</b>`) : text;
}
}
这篇关于垫自动完成过滤器以突出显示部分字符串匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!