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

pal*_*laa 5 datatable highlight angular-material 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);
}
Run Code Online (Sandbox Code Playgroud)

在材料数据表打字稿文件中,我将突出显示添加到构造函数中

constructor(
private highlight: HighlightSearchPipe,
 ) {}

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

您建议对突出显示搜索到的文本的数据表做什么?

Ian*_*n A 9

我已经设法制作了一个工作演示。我的HighlightSearchPipe课如下:

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">$1</strong>');
  }
}
Run Code Online (Sandbox Code Playgroud)

我修改了包含applyFilter()函数的Typescript 类,如下所示:

一世。添加了filterText类变量,以便可以在 HTML 中访问用户键入的过滤器文本。此变量在applyFilter()函数中更新

ii. 删除了对this.highlight.transform(this.dataSource.filter, this.searchKeyword);in的调用applyFilter()

@Component({
  ...
})
export class TableFilteringExample {
  ...
  filterText = '';

  applyFilter(filterValue: string) {
    this.filterText = filterValue.trim();
    this.dataSource.filter = this.filterText.toLowerCase();
  }
}
Run Code Online (Sandbox Code Playgroud)

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

<ng-container matColumnDef="name">
  <th mat-header-cell *matHeaderCellDef> Name </th>
  <td mat-cell *matCellDef="let element">{{element.name}}</td>
</ng-container>
Run Code Online (Sandbox Code Playgroud)

到:

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

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