首页 > 解决方案 > 更改指令输出格式

问题描述

我在 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 时,我需要该值只包含数字而不包含任何奇怪的字符。我该如何解决?

标签: angular

解决方案


好的,临时答案是:

        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;
            }
        }

让我知道你们是否有更好的解决方案


推荐阅读