[英]How to search for keywords from array and highlight all text in parent div tag using JavaScript
[英]How to highlight the search text in div
我正在研究角度。 我想在 html 中突出显示“Searchtxt”,Searchtxt 是一个保存搜索栏值的变量。 例如: Searchtxt="产品名称"
HTML代码:
<div class="row" *ngFor="let cmp of ApiResult;let i = index">
<div class="col-sm-12" id="{{cmp.pkCategoryMaster}}">
<h1 class="side_header">{{cmp.categoryName}}</h1>
<div class="subcat hp-subcat22 HP_1_1" *ngFor="let cmpsub of ApiResult[i].subCategory;let j = index">
<h2>{{cmpsub.SubCategoryName}}</h2>
<ul>
<li *ngFor="let cmpProd of ApiResult[i].subCategory[j].ProductCategory **|search: searchtxt** ;">
<a (click)="NavigateByHome(cmpProd.PkProductCategoryMaster);">
{{cmpProd.ProductCategory **| highlight: searchtxt**}}</a>
</li>
</ul>
</div>
</div>
</div>
TS代码:
var searchtxt=localStorage.getItem("productCategoryName");
管道.ts :
transform(ProductCategory: any, searchText: string): any[] {
if (!ProductCategory) {
return [];
}
if (!searchText) {
return ProductCategory;
}
const value = ProductCategory.replace(
searchText, `<div style='background-color:yellow'>${searchText}</div>`);
console.log('value', value);
return this._sanitizer.bypassSecurityTrustHtml(value);
}
看起来您只是将样式应用于列表中与特定值匹配的项目。 您可以使用 ngClass 有条件地应用您为组件定义的 CSS 类。
组件.scss
.highlight {
background-color:yellow;
}
组件.html
<li *ngFor="let cmpProd of ApiResult[i].subCategory[j].ProductCategory **|search:searchtxt** ;">
<a (click)="NavigateByHome(cmpProd.PkProductCategoryMaster);"
[ngClass]="{ 'highlight' : cmpProd.ProductCategory === searchTxt }">
{{cmpProd.ProductCategory}}
</a>
</li>
我不会使用管道来输出 html。 您已经看到您必须禁用安全检查,这应该作为警告,表明这不是正确的方法。 如果你想要一些可重用的东西,那么我会写一个组件而不是管道,但如果它所做的只是根据这种情况改变背景颜色,那么它可能是矫枉过正。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.