Angular: limitTo pipe not working

血红的双手。 提交于 2019-12-03 04:53:06

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

In order to answer to your question if it was removed: yes and no. limitTo seems to be removed, but there is a slice pipe which basically does the same as limitTo and can be used on strings aswell as on lists. It also gives you the oppurtunity to start your limitation at a given start index, which is neat.

In your case a simple {{ item.description | slice:0:20 }} would be enough. Unless you want to gain more experience writing your own pipe, which I even encourage ;)

Source and Documentation: https://angular.io/docs/ts/latest/api/common/index/SlicePipe-pipe.html

You can use ng2-truncate instead

It has more options such as: truncate by words, truncate by characters, truncate left side (...abc)....

$ npm install ng2-truncate --save

Declarations

import { Component } from '@angular/core';
import { TruncateModule } from 'ng2-truncate';

@Component({
    selector: 'my-component',
    template: '<p>{{ "123456789" | truncate : 3 }}</p>'
})
export class MyComponent {

}

@NgModule({
  imports: [ TruncateModule ],
  declarations: [ MyComponent ]
})
export class MyApp { }

Component

@Component({
    ...
    template: '<p>{{ "123456789" | truncate : 3 : "..." }}</p>',
    ...
})

Result:

<p>123...</p>

I added this code to make more sense

{{ item.description | slice:0:20 }}{{ item.description.length > 20 ? '....read more' : '' }}

to show that the data is sliced and contains more data that is hidden

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!