angular - 更改指令输出格式
问题描述
我在 angular 9 中制作了我在自定义组件中使用的下一个指令:
@Directive({
selector: '[number-behavior]',
})
export class NumberBehaviorDirective {
@Input() behaviorType: FeeViewType;
constructor(private el: TextBoxComponent) {}
@HostListener('focusout', ['$event'])
focusout(event: KeyboardEvent) {
this.formatValue();
event.preventDefault();
}
private formatValue() {
const conversion = this.parseValue();
if (Number.isNaN(conversion)) {
if (this.el !== undefined) {
this.el.value = '';
}
return;
}
this.el.value = conversion;
switch (this.behaviorType) {
case FeeViewType.Decimal:
const decimalValue = conversion / 100;
if (decimalValue % 1 === 0) {
if (this.el.dxTextBox !== undefined) {
this.el.dxTextBox.value = `${decimalValue}.00`;
}
return;
}
if (this.el.dxTextBox !== undefined) {
this.el.dxTextBox.value = (conversion / 100).toFixed(2);
}
break;
case FeeViewType.Percentage:
if (this.el.dxTextBox !== undefined) {
this.el.dxTextBox.value = `${conversion} %`;
}
break;
}
}
private parseValue(): number {
if (this.el.value === undefined) {
return Number.NaN;
}
const current: string = this.el.value.toString().replace(/[^\d]/g, '');
return Number.parseFloat(current);
}
}
更新
指令的作用是,如果收到一个数字,那么如果适用,它将变成百分比格式:例如:10 -> 10%。其他时间可以将其转换为具有两个位置的十进制值:10 -> 0.10。问题是,当我发送与指令关联的模型的数据时,我需要发送 10 的值,发送无用:10 % 或 0.10
一切正常,但是当我需要将值发送到 API 时,我需要该值只包含数字而不包含任何奇怪的字符。我该如何解决?
解决方案
好的,临时答案是:
for (const field of Object.keys(entity)) {
if (entity[field] === null) {
continue;
}
if (entity[field].toString().indexOf('%') !== -1) {
entity[field] = Number.parseFloat(entity[field].toString().replace(/[^\d]/g, ''));
continue;
}
if (entity[field].toString().indexOf('.') !== -1) {
entity[field] = Number.parseFloat(entity[field].toString().replace(/[^\d]/g, ''));
continue;
}
}
让我知道你们是否有更好的解决方案
推荐阅读
- python - 为什么我的 Python 脚本不提示用户输入?
- r - 在同一图上绘制密度图和散点图
- r - 如何根据另一个数据框中的部分字符串匹配向一个数据框添加一列?
- c# - 使用协程淡入/淡出 TextMeshPro 文本元素
- firebase - Sendgrid 和 Firebase 函数:发送带有动态模板数据的事务性电子邮件时出错
- html - 我怎样才能让一个div占据全身高度
- java - HashMap / ArrayList 每个键不会取多个值
- django - 自定义 Django 身份验证时出现密码错误
- mediawiki - Mediawiki中上传文件的可编程自动重命名?
- javascript - addEventListener 返回未定义