gpt4 book ai didi

Angular:来自指令的 updateValueAndValidity

转载 作者:太空狗 更新时间:2023-10-29 17:40:23 25 4
gpt4 key购买 nike

如果输入值是整数,我有一个附加小数点的指令。下面是实现。

import { Directive, ElementRef, Input, OnInit, HostListener, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Directive({
selector: '[price]',
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => PriceDirective),
multi: true
}
]
})
export class PriceDirective implements ControlValueAccessor {

constructor(private el: ElementRef) { }

// ControlValueAccessor interface
private _onChange = (_) => { };
private _onTouched = () => { };

@HostListener('blur', ['$event'])
input(event) {
!!event.target.value ? $(this.el.nativeElement).val(Number(event.target.value).toFixed(2)) : $(this.el.nativeElement).val(null);

this._onChange(parseFloat(event.target.value));
this._onTouched();
}
writeValue(value: any): void {
!!value ? $(this.el.nativeElement).val(Number(value).toFixed(2)) : $(this.el.nativeElement).val(null);
}

registerOnChange(fn: (_: any) => void): void { this._onChange = fn; }
registerOnTouched(fn: any): void { this._onTouched = fn; }

}

一切按预期进行。

但是,由于 Angular 在以编程方式更改值时不会触发验证,因此不会验证具有此指令的文本框。

在这种情况下,除了将 control 引用作为输入传递给指令并对其调用 updateValueAndValidity 或调用 之外,我如何启用验证>updateValueAndValidity inputblur

如果有人建议我从指令本身触发验证的方法,那就太好了。

最佳答案

我用这种方法解决了同样的问题。这是我的第一个方法。

  update() {

// ...

const el = this.el.nativeElement;
const reg = new RegExp(this.textMaskConfig.replacement);

el.value = this.prevStr.replace(reg, this.currentChar);

// ...

}

但它不会触发验证事件。所以我得到了 NgControl 组件并使用了 setValue() 方法。

  constructor(private el: ElementRef, private ctrl: NgControl) {   
}

@HostListener('keydown', ['$event']) onKeyDownHandler(e) {
this.ctrl.control.setValue(value);
}

关于Angular:来自指令的 updateValueAndValidity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48472868/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com