Search code examples
angularangular-filters

How to make excerpt filter in angular 2?


i'm new to angular 2 , i used to get the excerpt of a text in angularjs with a filter like this :

app.filters.js:

app.filter('excerpt', function () {
    return function (text, length) {
        if (text.length > length) {
            return text.substr(0, length) + '...';
        }
        return text;
    }
}); 

in html file :

{{blog.content | excerpt:90}}

what's the equivalent in angular 2 ?


Solution

  • This should be doing it :

    • First create your filter .ts file :

    excerpt.filter.ts

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
      name: 'excerpt',
      pure: false
    })
    export class ExcerptFilter implements PipeTransform {
      transform(text: String, length:any ): any {
        if (!text || !length) {
          return text;
        }
        if (text.length > length) {
          return text.substr(0, length) + '...';
        }
          return text;
    
      }
    }
    
    • Then you can use it like the following :

    template.component.html

    <div class="description">{{blog.content | excerpt:90}} </div>
    
    • Make sure that you're importing your filter in app.module.ts file :

      import {ExcerptFilter} from './filters/excerpt.filter';

    for more infos about creating pipes see the Docs