mat-autocomplete过滤器以高亮显示部分字符串匹配

Mat*_*ynn 11 typescript angular-material angular

我正在尝试使用mat-autocomplete类似于以下示例的过滤器;

贸易输入示例

所以我试图实现这个功能,这样当用户开始输入交易时,他们正在寻找基于字符串中任何地方的部分字符串匹配的过滤器,并在选项中突出显示.

cheackatrade截图

我目前在我的.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>
Run Code Online (Sandbox Code Playgroud)

我的.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);
}
Run Code Online (Sandbox Code Playgroud)

ICategory 是一个基本的界面.

export interface ICategory {
    value: number;
    name: string;  
}
Run Code Online (Sandbox Code Playgroud)

服务getCategories()只返回api中的所有类别.

根据这个例子,代码目前正在工作和构建;

Angular Material mat-autocomplete示例

我想在选项字符串中添加突出显示术语的效果?这有可能吗?

bug*_*ugs 18

只要用户键入过滤器中的某些内容,您就可以使用自定义管道突出显示部分匹配.

@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;
  }
}
Run Code Online (Sandbox Code Playgroud)

演示