Reputation: 19
I am working on angular. I want to highlight the "Searchtxt" in html, Searchtxt is a variable which holds the value of searchbar. Eg: Searchtxt="ProductName"
HTML code :
<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 code :
var searchtxt=localStorage.getItem("productCategoryName");
Pipe.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);
}
Upvotes: 0
Views: 452
Reputation: 7141
It looks like you're just applying a style to items in the list that match a particular value. You could just use ngClass to conditionally apply a CSS class that you define for the component.
component.scss
.highlight {
background-color:yellow;
}
component.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>
I wouldn't use a pipe to output html. You've already seen that you have to disable a security check which should act as a warning that this isn't the right way. If you want something that is reusable then I would write a component rather than a pipe but if all it does is change the background colour based on this condition then it's probably overkill.
Upvotes: 1