信使根据用户提供的输入显示搜索结果。需要高亮显示被搜索的词,同时显示结果。 这些是使用的 html 和组件。
Component.html
<div *ngFor = "let result of resultArray">
<div>Id : result.id </div>
<div>Summary : result.summary </div>
<div> Link : result.link </div>
</div>
Component.ts
resultArray : any = [{"id":"1","summary":"These are the results for the searched text","link":"http://www.example.com"}]
此 resultArray 是通过将搜索文本作为输入发送到后端服务中获取的。根据搜索文本,获取结果。需要高亮显示搜索到的文字,类似于google搜索。请找截图,
如果我搜索“member”一词,则会突出显示出现的“member”一词。如何使用 Angular 2 实现相同的效果。请就此提出一个想法。
最佳答案
您可以通过创建一个管道并将该管道应用到 ngfor
中数组的 summary 部分来做到这一点。以下是 Pipe
的代码:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'highlight'
})
export class HighlightSearch implements PipeTransform {
transform(value: any, args: any): any {
if (!args) {return value;}
var re = new RegExp(args, 'gi'); //'gi' for case insensitive and can use 'g' if you want the search to be case sensitive.
return value.replace(re, "<mark>$&</mark>");
}
}
然后在标记中将它应用于这样的字符串:
<div innerHTML="{{ str | highlight : 'search'}}"></div>
将“搜索”替换为您要突出显示的词。
希望这会有所帮助。
关于javascript - 突出显示搜索文本 - angular 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44961759/