我想突出显示搜索到列表中的单词,但是管道不使用css而是返回字符串,而是 会在黄色背景上打印并显示标记
<span class='highlight'>hello</span>
PIPE
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'FilterPipe'
})
export class FilterPipe implements PipeTransform {
transform(items: Array<any>, filter: any): any[] {
if (!filter) return items;
return items.filter(function(item){
if (item.desc.indexOf(filter) >= 0) {
item.desc= item.desc(new RegExp(filter, 'i'),"<span class='highlight'>" + filter + "</span>");
}
return item;
});
}
}
组件
<div *ngFor="let item of items | FilterPipe: filter">
<div>{{item.name}}</div>
<div> {{item.desc}}</div>
</div>
STACKBLITZ
https://stackblitz.com/edit/angular-a4a4ga?file=src%2Fapp%2Fapp.component.ts
答案 0 :(得分:0)
尝试使用innerHTML
属性
<div *ngFor="let item of items | FilterPipe: filter">
<div [innerHTML]="item.nombre | safeHtml"></div>
<div [innerHTML]="item.desc | safeHtml"></div>
</div>
将传递的HTML标记为受信任,以便Angulars DOM清理程序不会剥离部件 用类似
的管道@Pipe({name: 'safeHtml'})
export class Safe {
constructor(private sanitizer:DomSanitizer){}
transform(style) {
return this.sanitizer.bypassSecurityTrustStyle(style);
// return this.sanitizer.bypassSecurityTrustHtml(style);
// return this.sanitizer.bypassSecurityTrustXxx(style); - see docs
}
}