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

时间:2017-12-19 03:39:27

标签: html angular typescript pipe

我是Angular 2的新手。我正在努力完成与上面帖子中提到的Highlight the search text - angular 2相同的任务。 我已经创建了管道过滤器我的问题是我应该在哪里保留管道过滤器以及我应该在哪里放置内部html div。

复制问题:

信使根据用户提供的输入显示搜索结果。在显示结果时,需要突出显示已搜索的单词。这些是使用的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来命中后端服务。根据搜索文本,获取结果。需要突出显示搜索到的文字,类似于谷歌搜索。

我应该如何应用搜索过滤器以及我应该在哪里保留内部html?

2 个答案:

答案 0 :(得分:8)

有关案例的正则表达式替换有一些调整,但这是一个起点:

//our root app component
import {Component, NgModule, VERSION, Pipe, PipeTransform} from '@angular/core'
import {BrowserModule, DomSanitizer} from '@angular/platform-browser'

@Pipe({
    name: 'highlight'
})
export class HighlightSearch implements PipeTransform {
  constructor(private sanitizer: DomSanitizer){}

  transform(value: any, args: any): any {
    if (!args) {
      return value;
    }
    // Match in a case insensitive maneer
    const re = new RegExp(args, 'gi');
    const match = value.match(re);

    // If there's no match, just return the original value.
    if (!match) {
      return value;
    }

    const result = value.replace(re, "<mark>" + match[0] + "</mark>");
    return this.sanitizer.bypassSecurityTrustHtml(result);
  }
}

@Component({ 
  selector: 'my-app',
  template: `
    <input (input)="updateSearch($event)">
    <div *ngFor="let result of resultArray" [innerHTML]="result.summary | highlight: searchTerm"></div>
  `,
})
export class App {
  results: string[]
  searchTerm: string;
  constructor() {
    this.resultArray = [
      {
        "id": "1",
        "summary": "These are the results for the searched text",
        "link": "http://www.example.com"
      },
      {
        "id": "2",
        "summary": "Here are some more results you searched for",
        "link": "http://www.example.com"
      }
    ]
  }
  updateSearch(e) {
    this.searchTerm = e.target.value
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App, HighlightSearch ],
  bootstrap: [ App ]
})
export class AppModule {}

Plnkr

编辑:Plnkr似乎不高兴。 StackBlitz

答案 1 :(得分:0)

您可以轻松使用此指令

用法:

<label [jsonFilter]="search">{{text}}</label>

指令

import {
      AfterViewInit,
      Directive,
      ElementRef,
      Input,
      OnChanges,
      SimpleChanges
    } from '@angular/core';
    
    @Directive({
      selector: '[jsonFilter]'
    })
    export class FilterDirective implements OnChanges, AfterViewInit {
    
      @Input() jsonFilter = '';
      constructor(
        private el: ElementRef,
      ) {
      }
    
      ngOnChanges(changes: SimpleChanges) {
        this.ngAfterViewInit();
      }
    
      ngAfterViewInit() {
        const value = this.el.nativeElement?.innerText.split('\n').join('');
        if (!value) return;
        const re = new RegExp(this.jsonFilter, 'gi');
        const match = value.match(re);
        if (!match || match.some(x => !x)) {
          this.el.nativeElement.innerText = value;
        } else {
          this.el.nativeElement.innerHTML =  value.replace(re, "<mark>" + match[0] + "</mark>")
        }
    
      }
    
    }