2017-12-19 4 views
0

저는 Angular 2에 새로 입문했습니다. 위의 게시물에서 언급 한 내용과 동일한 작업을 Highlight the search text - angular 2 수행하려고합니다. 파이프 필터를 만들었습니다. 내 질문은 어디에서 파이프 필터를 유지해야하며, 내부 HTML div를 어디에 배치해야합니까?각도 2의 검색 텍스트 강조 표시

문제 복사 :

메신저는 사용자에 의해 제공된 입력에 기초하여 검색 결과를 표시한다. 결과를 표시하는 동안 검색된 단어를 강조 표시해야합니다. 이것은 사용 된 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 검색과 유사하게 검색된 텍스트를 강조 표시해야합니다.

검색 필터를 적용하고 내부 HTML을 어디에 보관해야합니까?

+0

당신이 문자열을 가져 와서에 필요한 HTML 태그를 표시하는 시도가 텍스트를 강조 표시 하시겠습니까? – GustavoAdolfo

답변

0

이 경우에 대한 정규식 교체로 할 몇 가지 비틀기가 있지만 여기 출발점입니다 :

//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 value = value.replace(re, "<mark>" + match[0] + "</mark>") 
    return this.sanitizer.bypassSecurityTrustHtml(value) 
    } 
} 

@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

+0

젠체하는 사람은 당신이 생명의 은인이라고 당신에게 이야기했다 :) 나는 당신에게 1 개의 빚이있다 :) :) 감사합니다. 톤. – JavaDeveloper