本篇angular2/ionic2 實現(xiàn)搜索結(jié)果中的搜索關(guān)鍵字高亮的示例,分享給大家,具體如下:
添加一個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,這個的目的是是數(shù)據(jù)在頁面上的綁定能夠safe的解析
html中使用方法:
<ion-label [innerHTML]="item.name | keyword:searchText"></ion-label>
注: 在標(biāo)簽里面用新的標(biāo)簽包起來,不然會有樣式問題; 要用innerHTML來綁定數(shù)據(jù)。
演示效果
開源項目地址:https://github.com/alex-0407/ionic3-awesome
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com