我需要一个通用的输入过滤器,这样我就不必每次都编写ng-model逻辑。
我的解决方案是:
<input type="text" [(ngModel)]="foo" input-filter="-?[0-9]*" />代码隐藏
import { Directive, Input, HostListener, ElementRef, Inject } from '@angular/core';
import { NgModel } from '@angular/forms';
@Directive({
selector: '[ngModel][input-filter]',
providers: [NgModel]
})
export class InputFilter {
@Input('input-filter') filter: string;
private regEx: RegExp;
private previousValue: string;
constructor(private element: ElementRef, private ngModel: NgModel) {
this.previousValue = '';
}
@HostListener('keydown', ['$event']) onKeyDown(event) {
if (!this.regEx) {
this.regEx = new RegExp(`^${this.filter}$`);
}
if(this.regEx.test(this.ngModel.value)) {
this.previousValue = this.ngModel.value;
}
}
@HostListener('keyup', ['$event']) onKeyUp(event) {
let e = <KeyboardEvent> event;
if(this.regEx.test(this.ngModel.value)) {
return;
} else {
this.ngModel.update.emit(this.previousValue);
}
}
}这个解决方案是有效的,但我很好奇是否有人有更好的方法。
有什么建议吗?
更新
我问得太早了。原始指令没有更新模型(愚蠢的我)。新代码确实更新了模型。
过滤器是通过input元素上的属性传入的。
发布于 2017-11-26 15:14:20
如果您正在尝试验证输入,并且不允许用户插入错误的值,那么您就走在了正确的道路上,但是您遗漏了一些要点。
您应该像添加本地验证器一样添加自定义验证器(例如: required)。
https://stackoverflow.com/questions/47492891
复制相似问题