javascript - 错误:模板解析错误:找不到管道“currencySeparator”
问题描述
当我尝试在模板中使用自定义管道时出现错误:
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:',':'.'}}像这样在模板中它给了我这个错误。
我怎样才能解决这个问题?
谢谢
解决方案
不需要在 AppModule 中导入 PipeModule,而是在使用管道的组件所在的模块中导入。
推荐阅读
- android - Android 多线程
- python - Python断言属性包含在字典中
- ios - UIScrollView 内的动态 UITableView
- emoji - 如何在节点上放置表情符号(图像)
- python - Python在数组中赋值
- javascript - 尝试在异步函数中传递值时出错(条带充电过程)
- python - Python 通过 pip3 安装包:分段错误
- node.js - “express-session 不推荐使用未定义的重新保存选项;提供重新保存选项 node_modules/admin-bro-expressjs/plugin.js:138:14”
- java - 运行 Spring Boot 应用程序时创建 bean 时出错
- reactjs - 在 React 中提交后将 textarea 设置为原始