我有一个使用角度十进制管道的自定义十进制格式管道。此管道是共享模块的一部分。我在功能模块中使用它,并在运行应用程序时没有提供程序错误。
如果有任何拼写错误,请忽略。
./双人床/pipes/custom.pipe.同时
import { DecimalPipe } from '@angular/common';
..
@Pipe({
name: 'customDecimalPipe'
})
...
export class CustomPipe {
constructor(public decimalPipe: DecimalPipe) {}
transform(value: any, format: any) {
...
}
./modules/shared.module.同时
import { CustomPipe } from '../pipes/custom.pipe';
...
@NgModule({
imports: [ .. ],
declarations: [ CustomPipe ],
exports: [ CustomPipe ]
})
export class SharedModule { }
我在其中一个组件中注入自定义管道并调用transform方法来获取转换后的值。共享模块导入到功能模块中。
如果要在组件中使用pipe的transform()
方法,还需要将CustomPipe
添加到模块的提供者:
import { CustomPipe } from '../pipes/custom.pipe';
...
@NgModule({
imports: [ .. ],
declarations: [ CustomPipe ],
exports: [ CustomPipe ],
providers: [ CustomPipe ]
})
export class SharedModule { }
除了将CustomPipe
添加到模块的提供者列表之外,另一种方法是添加到组件的提供者。如果您的自定义管道仅在少数组件中使用,这将非常有用。
import { CustomPipe } from '../pipes/custom.pipe';
...
@Component({
templateUrl: './some.component.html',
...
providers: [CustomPipe]
})
export class SomeComponent{
...
}
希望这可以帮助。
您还可以使管道可注入(与使用cli创建的服务完成相同):
import { Injectable, Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'customDecimalPipe'
})
@Injectable({
providedIn: 'root'
})
export class CustomPipe extends PipeTransform {
...
}