突出显示搜索文本 - angular 2

IT技术 javascript angular html typescript
2021-03-01 22:56:38

信使根据用户提供的输入显示搜索结果。需要突出显示搜索到的单词,同时显示结果。这些是使用的 html 和组件。

组件.html

 <div *ngFor = "let result of resultArray">
<div>Id : result.id </div>
<div>Summary : result.summary </div>
<div> Link : result.link </div>
</div>

组件.ts

resultArray : any = [{"id":"1","summary":"These are the results for the searched text","link":"http://www.example.com"}]

这个 resultArray 是通过发送搜索文本作为输入来访问后端服务的。根据搜索文本,获取结果。需要高亮搜索到的文字,类似google搜索。请找到截图,

在此处输入图片说明

如果我搜索“成员”这个词,“成员”这个词的出现就会突出显示。如何使用 angular 2 实现相同的效果。请对此提出建议。

6个回答

您可以通过创建一个管道并将该管道应用到数组里面汇总部分来做到这一点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>");
    }
}

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

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

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

希望这会有所帮助。

@Jeremy 补充说。感谢您的投入。
2021-04-23 22:56:38
@afe return value.replace(new RegExp(args, 'gi'), "<mark>$&</mark>"); 将替换为相同的案例
2021-04-26 22:56:38
清晰而简单的答案!
2021-04-29 22:56:38
搜索 . 将选择所有内容,并且不搜索任何内容将为每个字符创建标记(因为这很容易,一个简单的 if (!args) {return value;} 在函数的开头)
2021-05-02 22:56:38
这也会用搜索到的子字符串替换找到的子字符串,应用错误的情况。
2021-05-18 22:56:38

所选答案存在以下问题:

  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;
}
这与该词的多次出现不匹配,但它确实提供了一个很好的观点,即试图通过覆盖大小写来防止搜索消除。我提交了一个答案,该答案使用区分大小写的正则表达式来尝试解决该问题。当搜索很时髦时,又会回到不区分大小写的模式。
2021-05-19 22:56:38

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

突出显示的text.component.html

<mark *ngIf="matched">{{matched}}</mark>{{unmatched}}

突出显示的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);
            }
        }
    }
}

突出显示的text.component.css

mark {
    display: inline;
    margin: 0;
    padding: 0;       
    font-weight: 600;
}

用法

<highlighted-text [needle]=searchInput [haystack]=value></highlighted-text>

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

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

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;
    }
}

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

var searchTerms = searchKey.split(' ');

用法:

<div [innerHTML]="result | highlight:searchTerms"></div>

如果您想使用自定义类:

.highlight-search-text {
  color: black;
  font-weight: 600;
}

一切顺利!

提示:如果您更改"<mark>" + text + "</mark>""<mark>$&</mark>"它,将保留突出显示部分的大小写。
2021-04-21 22:56:38
应该[innerHTML]不是[innetHTML]
2021-05-11 22:56:38

基于以前的答案(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);
    }
}

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

<highlighted-text [needle]="searchInput" [haystack]="value"></highlighted-text>

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