本篇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来绑定数据。
演示效果
开源项目地址:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。
如对本文有疑问, 点击进行留言回复!!
解决三元运算符 报错“SyntaxError: can''t assign to conditional expression”
解决angular 使用原生拖拽页面卡顿及表单控件输入延迟问题
使用 Angular RouteReuseStrategy 缓存(路由)组件的实例代码
分享Angular http interceptors 拦截器使用(推荐)
网友评论