ionic2/ionic3 實現搜尋結果中的搜尋關鍵字高亮

全棧弄潮兒發表於2018-08-15

新增一個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來繫結資料。

演示效果

ionic3-awesome-v1.1.gif

開源專案地址: github.com/alex-0407/i…


更多angular1/2/4/5、ionic1/2/3/4、react、vue、微信小程式、nodejs等技術文章、視訊教程和開源專案,請掃一掃下面的二維碼關注微信公眾號——全棧弄潮兒

微信公眾號.png


前端最火框架排行榜——小程式二維碼

ionic2/ionic3 實現搜尋結果中的搜尋關鍵字高亮

相關文章