2017-07-07 75 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或別的東西。