Angular NgControl:如何为视图设置一个值并将其保留在模型中?

时间:2019-03-16 17:59:39

标签: angular angular-directive angular-forms

我已经制定了一条指令来对我的货币字段进行一些掩盖,并且我想确认是否可以通过掩盖来设置控件的视图值,而将我的模型值与数字本身保持一致。有可能吗?

我的指令如下:

@Directive({
    selector: '[myCurrencyMask]'
})
export class MyCurrencyMaskDirective implements OnInit, OnDestroy {

    private subscription: Subscription;

    constructor(public ngControl: NgControl) {}

    public ngOnInit() {
        const ctrl = this.ngControl.control;
        this.subscription = ctrl.valueChanges.subscribe((value) => {
            this.onInputChange(value);
        });
    }

    public ngOnDestroy() {
        this.subscription.unsubscribe();
    }

    public onInputChange(event) {
        let newVal = event.replace(/\D/g, '');

        // ...
        // skipping code here that mask the number as string..
        // ...


        // on this point, newVal is a string. 
        // I'd like to keep it on the view as this string, 
        // but on my model, I'd like to keep the variable as number..
        this.ngControl.control.setValue(newVal, { emitEvent: false});

    }
}

谢谢!

0 个答案:

没有答案