【发布时间】:2018-07-06 11:20:35
【问题描述】:
我有一个指令,如果输入值是整数,则在模糊时附加小数。下面是实现。
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 或在input 或blur 上调用updateValueAndValidity 之外,我如何才能启用验证。
如果有人建议我一种从指令本身触发验证的方法,那就太好了。
【问题讨论】:
-
好问题,我也有同样的问题。点赞!
标签: angular angular2-forms angular2-directives