我有一个自定义管道来突出显示文字。我想将此管道应用于ngfor迭代元素。我怎么能这样做?
这是我的代码:
import { PipeTransform, Pipe } from '@angular/core';
@Pipe({ name: 'highlight' })
export class HighlightPipe implements PipeTransform {
transform(text: string, search): string {
if (search && text) {
let pattern = search.toString().replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
pattern = pattern.split(' ').filter((t) => {
return t.length > 0;
}).join('|');
const regex = new RegExp(pattern, 'gi');
return text.toString().replace(regex, (match) => `<span class="search-highlight">${match}</span>`);
} else {
return text;
}
}
}
:host ::ng-deep .search-highlight{
background-color: #F2E366;
}
<tbody>
<tr *ngFor="let item of (itemsList | highlight)">
<td><i [ngClass]="{'fa fa-paperclip':item.ext === 'pdf'}"></i></td>
<td>{{item.name}}<span [innerHTML]="text | highlight: searchTerm"></span></td>
<td>{{item.path}}</td>
<td>{{item.dateModification | date:'short':'':'fr'}}</td>
</tr>
</tbody>
答案 0 :(得分:1)
在@ChellappanV评论之后,特别是这个one,我在search.component.html中更改了我的代码,如下所示:
<td>{{item.name}}<span [innerHTML]="item.name | highlight: searchTerm.value"></span></td>
而不是:
<td>{{item.name}}<span [innerHTML]="text | highlight: searchTerm"></span></td>