Nasser Boukehil
Nasser Boukehil

Reputation: 441

How to apply a custom pipe to ngFor iteration elements

I have a custom pipe to highlight text. I want to apply this pipe to ngfor iteration elements. How can I do that?

Here is my code:

import { PipeTransform, Pipe } from '@angular/core';

@Pipe({ name: 'highlight' })
export class HighlightPipe implements PipeTransform {
  transform(text: string, search): string {
    if (search && text) {
      let pattern = search.toString().replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
      pattern = pattern.split(' ').filter((t) => {
        return t.length > 0;
      }).join('|');
      const regex = new RegExp(pattern, 'gi');

      return text.toString().replace(regex, (match) => `<span class="search-highlight">${match}</span>`);
    } else {
      return text;
    }
  }
}
:host ::ng-deep .search-highlight{
  background-color: #F2E366;
}
  <tbody>
      <tr *ngFor="let item of (itemsList | highlight)">
          <td><i [ngClass]="{'fa fa-paperclip':item.ext === 'pdf'}"></i></td>
          <td>{{item.name}}<span [innerHTML]="text | highlight: searchTerm"></span></td>
          <td>{{item.path}}</td>
          <td>{{item.dateModification | date:'short':'':'fr'}}</td>
      </tr>
  </tbody>

Upvotes: 0

Views: 238

Answers (1)

Nasser Boukehil
Nasser Boukehil

Reputation: 441

After @ChellappanV comments, specially this one, I changed my code in the search.component.html as following:

<td>{{item.name}}<span [innerHTML]="item.name | highlight: searchTerm.value"></span></td>

instead of:

<td>{{item.name}}<span [innerHTML]="text | highlight: searchTerm"></span></td>

Upvotes: 1

Related Questions