【问题标题】:mat-autocomplete filter to hightlight partial string matchesmat-autocomplete 过滤器以突出显示部分字符串匹配
【发布时间】:2018-09-14 03:46:39
【问题描述】:

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

trade input example

所以我正在尝试实现该功能,以便当用户开始输入交易时,他们正在寻找基于字符串中任何位置的部分字符串匹配的过滤器,并在选项中突出显示。

我目前在我的 .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 返回所有类别。

代码当前正在运行并按照此示例构建;

Angular Material mat-autocomplete example

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

【问题讨论】:

    标签: angular typescript angular-material


    【解决方案1】:

    每当用户在过滤器中输入内容时,您都可以使用自定义管道突出显示部分匹配。

    @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;
      }
    }
    

    Demo

    【讨论】:

    • 这绝对是完美的,非常感谢代码。作为一个有角度的新手,我不知道管道。
    • 我收到错误,例如无法读取未定义的属性“替换”。你能帮我解决吗?
    【解决方案2】:

    要解决未定义的问题,您应该只检查搜索字符串的存在,有时您在控件上没有:

    export class HighlightPipe implements PipeTransform {
      transform(text: string, search): string {
      if (search && text && typeof search === 'string' && typeof text === 'string') {
          const pattern = search
            .replace(/[\-\[\]\/{}()*x+?.\\^$|]/g, '\\$&')
            .split(' ')
            .filter(t => t.length > 0)
            .join('|');
          const regex = new RegExp(pattern, 'gi');
          return search ? text.replace(regex, match => `<strong>${match}</strong>`) : text;
        }
        return text;
      }
    }
    

    还请注意,一些正则表达式已被精简,因为一些转义不是必需的。

    最后,您现在应该在 HTML 中使用 [innerHTML] 而不仅仅是管道对象文本:

    <mat-option [innerHTML]="optionText | highlight: searchValue"></mat-option>
    

    【讨论】:

      猜你喜欢
      • 2016-12-03
      • 2022-01-03
      • 2017-08-01
      • 2018-09-22
      • 2021-06-14
      • 1970-01-01
      • 1970-01-01
      • 2014-10-28
      • 1970-01-01
      相关资源
      最近更新 更多