输入字段仅接受数字,而输入其他角色时不会触发事件 [英] Input field accepting only numbers without firing events when input other caracters

查看:86
本文介绍了输入字段仅接受数字,而输入其他角色时不会触发事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对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在调用您的侦听器之前检测到此事件,因此停止传播不会影响您在父组件中对其进行响应的Angular事件(如ngModelChange).

我建议提供自己的事件以指示值更改,并在您真的希望发出该值时发出它:

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);
    }
  }

}

然后您可以将ngModelChanged绑定替换为numberChanged:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆