2017-07-07 61 views
0

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

` 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; 
    } 
}` 
+0

它是如何不工作的工作plunker?它是否产生错误?或者只是不缩短价值? – DeborahK

回答

1

首先在管

@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

+0

这个工作,我只需要删除将.length()更改为.length ....谢谢!正在思考在C++哈哈 –

0

你管本身看起来不错,但为了使用它,你必须将其导入到你的模块,并声明并导出它,所以它在你的组件提供。

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

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

}) 
export class SharedModule { } 

加入这个取其模块相应的设置,我把我所有的管道在SharedModule,所以这就是为什么这是出口SharedModule,但你可能有这样的MainModule或别的东西。