2016-01-27 24 views

risposta

14

Sì, è possibile utilizzare PLATFORM_PIPES per aggiungere una pipa personalizzata e denominare la pipa date per dirottarla.

@Pipe({ 
    name : 'date' // Hijacks the 'date' pipe 
}) 
class CustomDatePipe { 
    transform(val, args) { 
    return /* do something new with the value */; 
    } 
} 

@Component({ 
    selector: 'my-app', 
    template : '{{mydate | date}}', 
}) 
export class App { 
    mydate = Date.now(); 
} 

// Provides the CustomDatePipe globally 
bootstrap(App, [provide(PLATFORM_PIPES, {useValue: [CustomDatePipe], multi: true})]); 

In questo modo non sarà necessario aggiungere specificare ogni volta in pipes proprietà a componenti.

Ecco un plnkr con un esempio di lavoro.

+0

Sapete cosa è necessario fare in modo che i tubi siano anche disponibili globalmente nei test unitari? –

2

Sì, utilizzare PLATFORM_PIPES in modo seguente

https://angular.io/docs/ts/latest/api/core/index/PLATFORM_PIPES-let.html

risposta
import {PLATFORM_PIPES} from '@angular/core'; 
import {OtherPipe} from './myPipe'; 
@Component({ 
    selector: 'my-component', 
    template: ` 
    {{123 | other-pipe}} 
    ` 
}) 
export class MyComponent { 
    ... 
} 
bootstrap(MyComponent, [{provide: PLATFORM_PIPES, useValue: [OtherPipe], multi:true}]); 
1

Eric Martinez' funziona bene! Tieni presente che PLATFORM_PIPES è obsoleto in Angular4. I tubi della piattaforma in Angular4 sono configurati tramite app.modules:

/** 
* `AppModule` 
*/ 
@NgModule({ 
    ... 
    providers: [ 
     ... 
     CustomDatePipe 
    ] 
}) 
+0

E per i test (per rispondere alla domanda di Vilmantas Baranauskas): puoi scrivere un test per il tubo stesso e nel tuo test invocare esplicitamente la trasformazione, ad es. new CustomDatePipe(). transform (input) –

Problemi correlati