应用场景简介
我们在做搜索列表的相关需求时,大多的情况下都会要求将匹配的值进行<font color="red">高亮标红</font>显示,如下图所示,今天通过Angular中的一个小案例来实现这个功能~
相关代码展示
- 首先,我们在Angular中,可以通过写一个pipe来实现,将匹配到的内容进行高亮显示
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'highlightSearchResult',
})
export class HighlightSearchPipe implements PipeTransform {
public transform(value: string, args?: string): string {
const needMatchValue = args; // 用户在input框输入的值
let endValue = value; // 最终处理好并高亮标识的结果
const isEnglishReg = new RegExp('^[a-zA-Z]+$');
if (isEnglishReg.test(needMatchValue)) { // 输入拼音的情况
endValue = this.getEndMatchedValue(value, needMatchValue, value);
} else {
const searchValue = needMatchValue;
const regExp = new RegExp(searchValue, 'gi'); // 全局匹配忽略大小写
if (regExp.test(value)) {
endValue = this.getEndMatchedValue(value, needMatchValue, value);
}
}
return endValue;
}
public getEndMatchedValue(value: string, searchValue: string, oriValue: string): string {
if (searchValue) {
let endValue = oriValue;
const upperValue = value.toUpperCase();
const upperSearch = searchValue.toUpperCase();
const matchIndex = upperValue.indexOf(upperSearch);
if (matchIndex !== -1) {
// 将匹配到的内容进行高亮标注
endValue = oriValue.substring(0, matchIndex) +
`<span style="color: red">${oriValue.substring(matchIndex, matchIndex + searchValue.length)}</span>` +
oriValue.substring(matchIndex + searchValue.length);
}
return endValue;
} else {
return oriValue;
}
}
}
- 由于在html中我们需要将已经高亮的结果,通过innerhtml插入到原本的元素中,防止跨站点脚本安全漏洞(XSS)相关内容的正确显示,我们还需要写一个safe的pipe,代码也很简单,如下所示:
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeResourceUrl, SafeUrl } from '@angular/platform-browser';
@Pipe({
name: 'safe',
})
export class SafePipe implements PipeTransform {
constructor(private _sanitizer: DomSanitizer) {
}
public transform(value: any, type: string): SafeHtml | SafeStyle | SafeScript | SafeResourceUrl | SafeUrl {
switch (type) {
// 这条语句就是我们今天主要用到的
case 'html': return this._sanitizer.bypassSecurityTrustHtml(value);
// 接下来的这些是DomSanitizer提供的其他一些安全的转换
case 'style': return this._sanitizer.bypassSecurityTrustStyle(value);
case 'script': return this._sanitizer.bypassSecurityTrustScript(value);
case 'url': return this._sanitizer.bypassSecurityTrustUrl(value);
case 'resourceUrl': return this._sanitizer.bypassSecurityTrustResourceUrl(value);
default: throw new Error(`Invalid safe type specified: ${type}`);
}
}
}
- 最后我们来看一下,在html中怎么样使用这两个pipe,来实现我们的需求
<div class="search-popup" >
<div class="data-box" *ngIf="searchData && searchData.length !== 0">
<ul>
// 就是在这里啦~~~
<li
*ngFor="let item of searchData;let i = index;"
<span [innerHTML]="item | highlightSearchResult:searchValue | safe: 'html'"></span>
</li>
</ul>
</div>
</div>
网友评论