我的管道pipe都是统一引入到模块pipeModule中,再在app.module.ts中import这个模块的
umberUnit.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser'
@Pipe({
name: 'umberUnit'
})
export class UmberUnitPipe implements PipeTransform {
constructor(
private ppTest: DomSanitizer
) {}
transform(value: any, args?: any): any {
if (value < 1000) {
return value/100 + '百' + args
} else if (value < 10000) {
return value/1000 + '千' + args
}
}
}
pipeModule.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { PipeModuleComponent } from './pipeModule.component';
import { TranHtmlPipe } from '../tranHtml.pipe';
import { UmberUnitPipe } from '../umberUnit.pipe';
@NgModule({
imports: [
CommonModule
],
exports: [
TranHtmlPipe,
UmberUnitPipe
],
declarations: [
PipeModuleComponent,
TranHtmlPipe,
UmberUnitPipe
]
})
export class PipeModuleModule {
static forRoot() {
return {
ngModule: PipeModuleModule,
providers: [],
};
}
}
app.module.ts
正常情况下,此时就可以直接使用了
但是我发现用的时候一直报错
找了好久的原因,后来发现原来是新建pipe文件时的一个坑
建pipe文件两种方式:
1、ng g pipe numberUnit(通过密令新建就没坑)
2、vscode自带新建文件的功能 (我是通过第二种方式建的文件)
第二种方式与第一种的区别就是在app-routing.module.ts中也引入了该管道
所以就一直有上面的错误
所以建议新建管道 ,指令时还是通过密令,如果硬是通过vscode新建pipe的话记得把app-routing.module.ts中引入的pipe删掉;至于指令我还不知道会有什么坑,所以我在写的过程中还是会用vscode新建,先为大家趟趟水 ,踩踩坑。
已经给大家试过水了,指令和管道一样的。