- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
如果输入值是整数,我有一个附加小数点的指令。下面是实现。
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
input
或 blur
。
如果有人建议我从指令本身触发验证的方法,那就太好了。
最佳答案
我用这种方法解决了同样的问题。这是我的第一个方法。
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/
如果输入值是整数,我有一个附加小数点的指令。下面是实现。 import { Directive, ElementRef, Input, OnInit, HostListener, forwardRef
These docs说明如下: If emitEvent is true, this change will cause a valueChanges event on the FormControl
在我的 Angular 4 应用程序中,我有一个包含多个控件的表单。 在某些时候我需要强制更新它们的有效性,所以我在做: this.form.get('control1').updateValueAn
我试图根据某些条件在formGroup控件中添加和删除验证器。 当我通过formGroup.updateValueAndValidity()更新验证程序以使其整体不更新时,好像我正在为每个控件(即fo
我正在尝试使用 FormControls 在 Angular2 中进行日期验证。我有一个开始和结束日期。我需要验证开始日期是否在结束日期之前。以下是当控件的值发生变化时我如何编辑控件上的验证器: th
我升级到 rc.4 并尝试使用新的 forms-api。这是我得到的: “类型错误:this.form.updateValueAndValidity 不是函数” 异常起源于 Angular 内的“fo
我是一名优秀的程序员,十分优秀!