当输入其他字符时,输入字段只接受数字而不触发事件 [英] Input field accepting only numbers without firing events when input other caracters
问题描述
我对 html 数字输入的默认行为不满意,我想要一个只接受数字的简单输入.
I'm not satisfied with the default behavior of the html number input, I would like to have a simple input that accepts only numbers.
我创建了这个指令:
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
import { NgControl } from '@angular/forms';
@Directive({
selector: 'input[numbersOnly]'
})
export class NumberDirective {
constructor(private _el: ElementRef) { }
@HostListener('input', ['$event']) onInputChange(event) {
const initalValue = this._el.nativeElement.value;
this._el.nativeElement.value = initalValue.replace(/[^0-9]*/g, '');
if ( initalValue !== this._el.nativeElement.value) {
event.stopPropagation();
}
}
}
我面临的问题是event.stopPropagation()"不会停止事件传播,即使从用户的角度来看输入值没有改变,也会触发事件.
The issue I'm facing is that the "event.stopPropagation()" does not stop the event propagation, an event is fired even if the input value does not change from the user point of view.
当字段值没有改变时,如何停止事件传播?
How can I stop the event propagation when the field value has not changed ?
为了更好地理解,这里有一个 stackblitz 示例:https://stackblitz.com/edit/angular-numbers-only-directive
Edit : For better understanding, here is a stackblitz example : https://stackblitz.com/edit/angular-numbers-only-directive
推荐答案
我真的不认为有办法使用带有 HostListener
的指令来停止这个事件.
I don't really think there is a way to stop this event using directive with HostListener
.
Angular 在您调用侦听器之前检测到此事件,因此停止传播不会影响像 (没有证据,所以我可能错了)ngModelChange
这样您在父组件中做出反应的 Angular 事件.
Angular detected this event before you listener was called so stopping propagation will not affect Angular events like (no proof for that so I may be wrong)ngModelChange
to which you react in parent component.
我建议提供自己的指示值更改的事件,并在您确实希望它被发出时发出它:
I would suggest to provide own event indicating value change and emit it when you really want it to be emitted:
export class NumberDirective {
@Output() numberChanged = new EventEmitter<number>();
constructor(private _el: ElementRef) { }
@HostListener('input', ['$event']) onInputChange(event) {
const initalValue = this._el.nativeElement.value;
this._el.nativeElement.value = initalValue.replace(/[^0-9]*/g, '');
if ( initalValue === this._el.nativeElement.value) {
this.numberChanged.emit(initalValue);
}
}
}
然后你可以用 numberChanged
替换 ngModelChanged
绑定:
Then you can replace ngModelChanged
binding with numberChanged
:
<input type="text" [ngModel]="value" (numberChanged)="onChange($event)" numbersOnly/>
演示:https://stackblitz.com/edit/angular-numbers-only-directive-a2mv6e
这篇关于当输入其他字符时,输入字段只接受数字而不触发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!