本篇angular2/ionic2 實現搜索結果中的搜索關鍵字高亮的示例,分享給大家,具體如下:
添加一個pipe:
import { Pipe, Injectable, PipeTransform } from '@angular/core'; import { DomSanitizer } from '@angular/platform-browser'; @Pipe({ name: 'keyword' }) @Injectable() export class KeywordPipe implements PipeTransform { constructor(private sanitizer: DomSanitizer) { } transform(val: string, keyword: string): any { const Reg = new RegExp(keyword, 'i'); if (val) { const res = val.replace(Reg, `<span style="color: #81E1B7;">${keyword}</span>`); console.log(res); return this.sanitizer.bypassSecurityTrustHtml(res); } } }
注: DomSanitizer,這個的目的是是數據在頁面上的綁定能夠safe的解析
html中使用方法:
<ion-label [innerHTML]="item.name | keyword:searchText"></ion-label>
注: 在標簽里面用新的標簽包起來,不然會有樣式問題; 要用innerHTML來綁定數據。
演示效果
開源項目地址:https://github.com/alex-0407/ionic3-awesome
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com