当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > angular2/ionic2 实现搜索结果中的搜索关键字高亮的示例

angular2/ionic2 实现搜索结果中的搜索关键字高亮的示例

2018年09月23日  | 移动技术网IT编程  | 我要评论

本篇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来绑定数据。

演示效果

开源项目地址:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网