Yuvals Yuvals - 1 month ago 56
AngularJS Question

Angular2: limitTo pipe not working

I am trying to run

limitTo
pipe on Angular2 on a string:

{{ item.description | limitTo : 20 }}


And I get the following error:

The pipe 'limitTo' could not be found


Is it possible that this pipe was removed in Angular2?



This is my
app.module


import { TruncatePipe } from './limit-to.pipe';

@NgModule({
imports: [
BrowserModule,
FormsModule,
HttpModule,
InMemoryWebApiModule.forRoot(InMemoryDataService),
RouterModule.forRoot([
{
path: '',
redirectTo: '/home',
pathMatch: 'full'
},
{
path: 'home',
component: GridComponent
},
])
],
declarations: [
AppComponent,
TopNavComponent,
GridComponent,
TruncatePipe
],
providers: [
PinService,
],
bootstrap: [ AppComponent ]
})
export class AppModule { }


My grid component that is using the pipe:

import { Component,OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
moduleId : module.id,
selector: 'my-grid',
templateUrl : 'grid.component.html',
styleUrls: [ 'grid.component.css']
})

export class GridComponent implements OnInit{


constructor(
private router: Router,
private gridService: GridService) {
}

ngOnInit(): void {
}
}


My Pipe definition:

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

@Pipe({
name: 'limitToPipe'
})
export class TruncatePipe implements PipeTransform {

transform(value: string, limit: number) : string {

let trail = '...';

return value.length > limit ? value.substring(0, limit) + trail : value;
}

}


And finally my template:

<div *ngFor="let item of items" class="grid-item">
<p class="simple-item-description">
{{ item.description | limitToPipe : 20 }}
</p>
</div>

Answer

First you need to create a pipe.

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

@Pipe({
  name: 'limitTo'
})
export class TruncatePipe {
  transform(value: string, args: string) : string {
    // let limit = args.length > 0 ? parseInt(args[0], 10) : 10;
    // let trail = args.length > 1 ? args[1] : '...';
    let limit = args ? parseInt(args, 10) : 10;
    let trail = '...';

    return value.length > limit ? value.substring(0, limit) + trail : value;
  }
}

Add the pipe in the module.ts file

import { NgModule }      from '@angular/core';
import {  TruncatePipe }   from './app.pipe';

@NgModule({
  imports:      [
  ],
  declarations: [
    TruncatePipe
  ],
  exports: [ 
  ]
})

export class AppModule { }

Then use the pipe in the binding code:

{{ item.description | limitTo : 20 }} 

Demo plunker

Comments