突出显示搜索文本 - 角度2

reg*_*na 21 javascript html5 typescript angular

信使根据用户提供的输入显示搜索结果.在显示结果时,需要突出显示已搜索的单词.这些是使用的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>
Run Code Online (Sandbox Code Playgroud)

Component.ts

resultArray : any = [{"id":"1","summary":"These are the results for the searched text","link":"http://www.example.com"}]
Run Code Online (Sandbox Code Playgroud)

通过发送搜索文本作为输入来获取此resultArray来命中后端服务.根据搜索文本,获取结果.需要突出显示搜索到的文字,类似于谷歌搜索.请找截图,

在此输入图像描述

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

Fah*_*sar 40

您可以通过创建管道并将该管道应用于内部数组的摘要部分来实现ngfor.这是以下代码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>");
    }
}
Run Code Online (Sandbox Code Playgroud)

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

<div innerHTML="{{ str | highlight : 'search'}}"></div>
Run Code Online (Sandbox Code Playgroud)

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

希望这会有所帮助.

  • @afe return value.replace(new RegExp(args,'gi'),"<mark> $&</ mark>"); 将替换相同的情况 (6认同)
  • 这也会将搜索到的子字符串替换为找到的子字符串,并应用错误的大小写. (5认同)
  • 清晰而简单的答案! (2认同)

Kam*_*aad 9

所选答案存在以下问题:

  1. 如果搜索字符串中没有提供任何内容,它将返回undefined
  2. 搜索应该不区分大小写,但不应替换原始字符串大小写.

我会建议以下代码

transform(value: string, args: string): any {
    if (args && value) {
        let startIndex = value.toLowerCase().indexOf(args.toLowerCase());
        if (startIndex != -1) {
            let endLength = args.length;
            let matchingString = value.substr(startIndex, endLength);
            return value.replace(matchingString, "<mark>" + matchingString + "</mark>");
        }

    }
    return value;
}
Run Code Online (Sandbox Code Playgroud)


Rah*_*ane 6

如果您的字符串中有多个单词,请使用接受数组并突出显示结果中的每个单词的管道。

您可以将以下管道用于多个搜索词:-

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

@Pipe({
    name: 'highlight'
})

export class HighlightText implements PipeTransform {

    transform(value: any, args: any): any {
        if (!args) {return value;}
        for(const text of args) {
            var reText = new RegExp(text, 'gi');
            value = value.replace(reText, "<mark>" + text + "</mark>");
            //for your custom css
            // value = value.replace(reText, "<span class='highlight-search-text'>" + text + "</span>"); 


        }
        return value;
    }
}
Run Code Online (Sandbox Code Playgroud)

拆分您的字符串以生成字符串数组。

var searchTerms = searchKey.split(' ');
Run Code Online (Sandbox Code Playgroud)

用法:

<div [innerHTML]="result | highlight:searchTerms"></div>
Run Code Online (Sandbox Code Playgroud)

如果您想使用自定义类:

.highlight-search-text {
  color: black;
  font-weight: 600;
}
Run Code Online (Sandbox Code Playgroud)

祝一切顺利!

  • 提示:如果将 `"&lt;mark&gt;" + text + "&lt;/mark&gt;"` 更改为 `"&lt;mark&gt;$&amp;&lt;/mark&gt;"` ,它将保留突出显示部分的大小写。 (2认同)

Wil*_*ver 5

innerHTML 方法的难点之一是<mark>标记样式。另一种方法是将其放置在组件中,从而在样式中提供更多选项。

突出显示的text.component.html

<mark *ngIf="matched">{{matched}}</mark>{{unmatched}}
Run Code Online (Sandbox Code Playgroud)

突出显示的text.component.ts

import { Component, Input, OnChanges, OnInit } from "@angular/core";

@Component({
    selector: "highlighted-text",
    templateUrl: "./highlighted-text.component.html",
    styleUrls: ["./highlighted-text.component.css"]
})
export class HighlightedTextComponent implements OnChanges {
    @Input() needle: String;
    @Input() haystack: String;
    public matched;
    public unmatched;

    ngOnChanges(changes) {
        this.match();
    }

    match() {
        this.matched = undefined;
        this.unmatched = this.haystack;
        if (this.needle && this.haystack) {
            const needle = String(this.needle);
            const haystack = String(this.haystack);
            const startIndex = haystack.toLowerCase().indexOf(needle.toLowerCase());
            if (startIndex !== -1) {
                const endLength = needle.length;
                this.matched = haystack.substr(startIndex, endLength);
                this.unmatched = haystack.substr(needle.length);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

突出显示的text.component.css

mark {
    display: inline;
    margin: 0;
    padding: 0;       
    font-weight: 600;
}
Run Code Online (Sandbox Code Playgroud)

用法

<highlighted-text [needle]=searchInput [haystack]=value></highlighted-text>
Run Code Online (Sandbox Code Playgroud)


Tob*_*ann 5

基于以前的答案(HighlightedText-Component),我最终得到了这个:

import { Component, Input, OnChanges } from "@angular/core";

@Component({
    selector: 'highlighted-text',
    template: `
        <ng-container *ngFor="let match of result">
            <mark *ngIf="(match === needle); else nomatch">{{match}}</mark>
            <ng-template #nomatch>{{match}}</ng-template>
        </ng-container>
    `,
})
export class HighlightedTextComponent implements OnChanges {
    @Input() needle: string;
    @Input() haystack: string;
    public result: string[];

    ngOnChanges() {
        const regEx = new RegExp('(' + this.needle + ')', 'i');
        this.result = this.haystack.split(regEx);
    }
}
Run Code Online (Sandbox Code Playgroud)

这样,针的多个匹配也会突出显示。这个组件的用法和上一个回答类似:

<highlighted-text [needle]="searchInput" [haystack]="value"></highlighted-text>
Run Code Online (Sandbox Code Playgroud)

对我来说,这种使用组件的方法感觉更安全,因为我不必使用“innerHtml”。