新建立一个管道 keyword.pipe.ts
import {Injectable, Pipe, PipeTransform} from '@angular/core';
import {DomSanitizer} from '@angular/platform-browser';
@Pipe({
name: 'keyword'
})
@Injectable()
export class SearchkeywordPipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) {
}
transform(val: string, keyword: string): any {
const Reg = new RegExp(keyword, 'g');
if (val) {
const objToStr = JSON.stringify(val);
const res = objToStr.replace(Reg, `<a style="background:yellow;">${keyword}</a>`);
return this.sanitizer.bypassSecurityTrustHtml(res);
}
}
}
在需要使用的页面引入
import { keyword } from '../../../../pipe/keyword.pipe';
页面中使用
<div class="queryTxet" [innerHTML]="data._source | keyword: dataText"></div>
ok