突出显示搜索文本 - 角度2 [英] Highlight the search text - angular 2

查看:114
本文介绍了突出显示搜索文本 - 角度2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个messenger根据用户给出的输入显示搜索结果。在显示结果时,需要突出显示搜索到的单词。
这些是已使用的html和组件。

A messenger displays the search results based on the input given by the user. Need to highlight the word that is been searched, while displaying the result. These are the html and component that is been used.

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搜索。请找到截图,

This resultArray is fetched from hitting the backend service by sending the search text as input. Based on the search text, the result is fetched. Need to highlight the searched text, similar to google search. Please find the screenshot,

如果我搜索单词成员,成员一词的出现突出显示。如何使用角度实现相同2.请提出一个想法。

If I search for the word "member", the occurence of the word "member" gets highlighted. How to achieve the same using angular 2. Please suggest an idea on this.

推荐答案

您可以通过创建管道和将该管道应用于 ngfor 内的摘要部分数组。以下是 Pipe 的代码:

You can do that by creating a pipe and applying that pipe to the summary part of array inside ngfor. Here is the code for Pipe:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'highlight'
})

export class HighlightSearch implements PipeTransform {

    transform(value: any, args: any): any {
        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>" + args + "</mark>");
    }
}

然后在标记中将它应用于这样的字符串:

and then in markup apply it on a string like this:

<div innerHTML="{{ str | highlight : 'search'}}"></div>

将搜索替换为您要突出显示的单词。

Replace 'search' with the word you want to highlight.

希望这会有所帮助。

这篇关于突出显示搜索文本 - 角度2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆