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

html中使用方法:

<ion-label [innerHTML]="item.name | keyword:searchText"></ion-label>

注: 在<ion-item>标签里面用新的标签包起来,否则会有样式问题; 要用innerHTML来绑定数据。vue

演示效果

ionic3-awesome-v1.1.gif

开源项目地址: https://github.com/alex-0407/...node


更多angular1/2/4/五、ionic1/2/3/四、react、vue、微信小程序、nodejs等技术文章、视频教程和开源项目,请扫一扫下面的二维码关注微信公众号——全栈弄潮儿react

微信公众号.png


福利专区:扫码关注,免费领取淘宝天猫内部优惠券git

淘宝天猫内部优惠券.png

相关文章
相关标签/搜索