[英]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.