我是 Angular 2 的新手。我正在尝试完成与 Highlight the search text - angular 2 相同的任务。上面帖子中提到的内容。 我已经创建了管道过滤器,我的问题是管道过滤器应该放在哪里,内部 html div 应该放在哪里。
复制问题:
信使根据用户提供的输入显示搜索结果。需要高亮显示被搜索的词,同时显示结果。这些是使用的 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搜索。
我应该如何应用搜索过滤器以及我应该将内部 html 保存在哪里?
最佳答案
关于大小写的正则表达式替换有一些调整,但这里是一个起点:
//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 似乎不高兴。 StackBlitz
关于html - 以 Angular 2 突出显示搜索文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47879704/