本文介绍了角度:limitTo管道不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在字符串上的Angular2上运行limitTo管道:

I am trying to run limitTo pipe on Angular2 on a string:

{{ item.description | limitTo : 20 }}

然后出现以下错误:

The pipe 'limitTo' could not be found

是否可以在Angular2中删除该管道?

这是我的app.module

从'./limit-to.pipe'导入{TruncatePipe};

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 {
    }
}

我的管道定义:

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;
  }

}

最后是我的模板:

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

推荐答案

首先,您需要创建一个管道.

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;
  }
}

将管道添加到module.ts文件中

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 }}

演示朋克车

这篇关于角度:limitTo管道不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 15:11