mark search string dynamically using angular.js

前端 未结 4 2140
北荒
北荒 2021-02-08 07:22

How can I mark my search pattern dynamically in my html?
Example:

\"SearchExample\"

I\'m using angular

4条回答
  •  春和景丽
    2021-02-08 07:51

    Just in case that someone (like me a moment ago) needs this for angular2:

    highlight-pipe.ts:

    import {Pipe, PipeTransform} from '@angular/core';
    
    @Pipe({name: 'highlightPipe'})
    export class HighlightPipe implements PipeTransform{
    
      transform(text:string, filter:string) : any{
        if(filter){
          text = text.replace(new RegExp('('+filter+')', 'gi'), '$1');
        }
        return text;
      }
    }
    

    and use it like this:

    at top of file:

    import {HighlightPipe} from './highlight-pipe';
    

    in template where 'yourText' is the original text and 'filter' is the part you want to highlight:

    in component:

    pipes: [HighlightPipe]
    

    EDIT: I updated it for RC 4 and created a plunker for testing: http://plnkr.co/edit/SeNsuwFUUqZIHllP9nT0?p=preview

提交回复
热议问题