自定义角4管不工作

时间:2017-07-07 23:01:31

标签: angular

我缩短字符串的自定义管道不起作用。我已将其包含在我的app.module声明中并将其导入我的组件中。代码如下。

 `   import { Pipe, PipeTransform } from '@angular/core';
/*
  Takes a string and replaces it with a shortend version based on the length you give it if its greater than 14 char for Example
  someString = "hey whats up my name is Bob and im from Bob town"
  {{value | shortString : length of new string}}
  {{someString | shortString: 10}}
*/
@Pipe({name: 'shortString'})
export class shortString implements PipeTransform {
  transform(value: any, length: number): string {
    console.log('expected new string '+value.slice(0,length)+'...');
    return (value.length()>14)?value.slice(0,length)+'...': value;
  }
}`

2 个答案:

答案 0 :(得分:3)

管道中的第一个

@Pipe({name: 'shortString'})
export class shortString implements PipeTransform {
  transform(value: any, length: number): string {
    return (value.length()>14)?value.slice(0,length)+'...': value; // remove the length() it will be value.length
  }
}`

同样的工作人员

https://plnkr.co/edit/Xz528J1sCi7GlDeWELph?p=preview

答案 1 :(得分:1)

你的烟斗本身看起来很好,但为了使用它,你必须将它导入你的模块,然后声明并导出它,以便它可以在你的组件中使用。

import { shortString } from './shortString.pipe';

@NgModule({
    imports: [
    ],
    declarations: [
        shortString
    ],
    exports: [
        shortString
    ],
    providers: [
    ]

})
export class SharedModule { }

将此添加到适合您的设置的模块中,我将所有管道都放在SharedModule中,这就是为什么这会导出SharedModule,但您可能在MainModule中有这个。或者其他。