尝试在模板中使用自定义管道时出现错误:
Error: Template parse errors:
The pipe 'currencySeperator' could not be found
这里是CurrencySeperatorPipe
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'currencySeperator'
})
export class CurrencySeperatorPipe implements PipeTransform {
transform(value: any, decimalSp: string = ',', thousandSp: string = '.'): number {
return this.localeString(value,decimalSp,thousandSp);
}
missingOneDecimalCheck(nStr) {
nStr += '';
const x = nStr.split(',')[1];
if (x && x.length === 1) return true;
return false;
}
missingAllDecimalsCheck(nStr) {
nStr += '';
const x = nStr.split(',')[1];
if (!x) return true;
return false;
}
localeString(nStr,decimalSp,thousandSp) {
if (nStr === '') return '';
let x, x1, x2, rgx, y1, y2;
nStr += '';
x = nStr.split(thousandSp);
x1 = x[0];
x2 = x.length > 1 ? decimalSp + x[1] : '';
rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + thousandSp + '$2');
}
/** If value was inputed by user, it could have many decimals(up to 7)
so we need to reformat previous x1 results */
if (x1.indexOf(decimalSp) !== -1) {
y1 = x1.slice(x1.lastIndexOf(decimalSp)).replace(/\./g, '');
y2 = x1.split(decimalSp);
x = y2[0] + y1;
} else {
x = x1 + x2;
if (this.missingOneDecimalCheck(x)) return x += '0';
if (this.missingAllDecimalsCheck(x)) return x += `${decimalSp}00`;
}
return x;
}
}
所以我创建了 pipe.module.ts :
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { CurrencySeperatorPipe } from './currency-seperator.pipe';
@NgModule({
declarations: [CurrencySeperatorPipe],
imports: [],
exports:[CurrencySeperatorPipe]
})
export class PipeModule {
static forRoot() {
return {
ngModule: PipeModule,
providers: [],
};
}
}
我将此模块导入了 app.module.ts
@NgModule({
declarations: [
AppComponent
],
imports: [
...
PipeModule.forRoot(),
],
providers: [],
bootstrap: [AppComponent],
entryComponents: [
ModalComponent,
LoginComponent
],
})
export class AppModule { }
当我尝试使用 {{price | currencySeperator:',':'。'}} 像这样在模板中给我这个错误。
我该如何解决?
谢谢
答案 0 :(得分:0)
您不需要在AppModule中导入PipeModule,而是在使用管道的组件所属的模块中导入。