如何为 material 数据表过滤器应用突出显示

How to apply highlight for material datatable filter

我想突出显示在数据table 筛选字段中搜索的文本,我正在使用 material 数据 table 和 angular。 我为突出显示创建了一个管道,并将文本搜索作为 arg

发送
export class HighlightSearchPipe implements PipeTransform {
 private destroyed$: Subject<void> = new ReplaySubject(1);

 constructor( private sanitizer: DomSanitizer) {}

transform(value: any, args?: any): any {
   if (!value) {
   return observableOf(value);
  }

/** Data table filtering */
if (args) {
  const searchText = args[0];
  const re = new RegExp(searchText, 'gi');
  const match = value.match(re);
  // If there's no match, just return the original value.
  if (!match) {
    return value;
  }
  value = value.replace(re, '<mark class="saqr-first-mark">' + match[0] + '</mark>');
  return observableOf(value);
}

并且在 material 数据table 打字稿文件中,我将突出显示添加到构造函数中

constructor(
private highlight: HighlightSearchPipe,
 ) {}

applyFilter() {
 this.dataSource.filter = this.searchKeyword.trim().toLowerCase();
 this.highlight.transform(this.dataSource.filter, this.searchKeyword);  
// here cannot detect that 
}

您建议如何处理数据 table 突出显示搜索到的文本?

我已经成功制作了一个 working demo。我的HighlightSearchPipeclass如下:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'highlightSearch'
})
export class HighlightSearchPipe implements PipeTransform {

  transform(value: string, search: string): string {
    const valueStr = value + ''; // Ensure numeric values are converted to strings
    return valueStr.replace(new RegExp('(?![^&;]+;)(?!<[^<>]*)(' + search + ')(?![^<>]*>)(?![^&;]+;)', 'gi'), '<strong class="your-class"></strong>');
  }
}

我修改了包含 applyFilter() 函数的 Typescript class 如下:

我。添加了 filterText class 变量,以便可以在 HTML 中访问用户键入的过滤文本。此变量在 applyFilter() 函数

中更新

二。在 applyFilter()

中删除了对 this.highlight.transform(this.dataSource.filter, this.searchKeyword); 的调用
@Component({
  ...
})
export class TableFilteringExample {
  ...
  filterText = '';

  applyFilter(filterValue: string) {
    this.filterText = filterValue.trim();
    this.dataSource.filter = this.filterText.toLowerCase();
  }
}

在组件 HTML 中,我更改了单元格的渲染方式:

<ng-container matColumnDef="name">
  <th mat-header-cell *matHeaderCellDef> Name </th>
  <td mat-cell *matCellDef="let element">{{element.name}}</td>
</ng-container>

至:

<ng-container matColumnDef="name">
  <th mat-header-cell *matHeaderCellDef> Name </th>
  <td mat-cell *matCellDef="let element" [innerHTML]="element.name | highlightSearch: filterText"></td>
</ng-container>

这样单元格值(在本例中为 element.name)能够呈现 HTML。它使用 highlightSearch 管道来转换值并突出显示与过滤器匹配的部分。