没有自定义管道供应商-角4

我有一个自定义的十进制格式管道,使用角十进制管道内翻。这个管道是共享模块的一部分。我在特性模块中使用它,并且在运行应用程序时没有得到提供者错误。

如有任何输入错误,请忽略。

./src/tube/custom.pipe.ts

import { DecimalPipe } from '@angular/common';
..
@Pipe({
name: 'customDecimalPipe'
})
...
export class CustomPipe {
constructor(public decimalPipe: DecimalPipe) {}
transform(value: any, format: any) {
...
}

./module/shared.module.ts

import  { CustomPipe } from '../pipes/custom.pipe';


...


@NgModule({
imports:      [ .. ],
declarations: [ CustomPipe ],
exports:    [ CustomPipe ]
})
export class SharedModule { }

我将自定义管道注入其中一个组件并调用转换方法以获得转换后的值。在特征模块中导入共享模块。

53623 次浏览

If you want to use pipe's transform() method in component, you also need to add CustomPipe to module's providers:

import  { CustomPipe } from '../pipes/custom.pipe';


...


@NgModule({
imports:      [ .. ],
declarations: [ CustomPipe ],
exports:    [ CustomPipe ],
providers:    [ CustomPipe ]
})
export class SharedModule { }

Apart from adding the CustomPipe to the module's provider list, an alternative is to add to the component's providers. This can be helpful if your custom pipe is used in only a few components.

import  { CustomPipe } from '../pipes/custom.pipe';
...
@Component({
templateUrl: './some.component.html',
...
providers: [CustomPipe]
})
export class SomeComponent{
...
}

Hope this helps.

You could also make the pipe Injectable (the same way it is done with the services you create using the cli):

    import { Injectable, Pipe, PipeTransform } from '@angular/core';


@Pipe({
name: 'customDecimalPipe'
})
@Injectable({
providedIn: 'root'
})
export class CustomPipe extends PipeTransform {
...
}