I am trying to implement an input field, where only number keys are allowed.
(我正在尝试实现一个仅允许数字键输入的输入字段。)
For that I have successfully implemented the Numbers only validation in Forms. (为此,我已经成功地在表格中实施了仅数字验证。)
But here the requirement is that no other keys should work except the number keys.
(但是这里的要求是除数字键外,其他键都不能工作。)
For that I have tied to implement a @HostListener (为此,我不得不实现一个@HostListener)
In this case, when we click on alphabet keys, it does not show in the input field, but the value get assigned which that alphabet.
(在这种情况下,当我们单击字母键时,它不会显示在输入字段中,但是会为该字母分配值。)
Please check the code: HostListener code:
(请检查代码:HostListener代码:)
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();
}
}
}
HTML :
(HTML:)
Type anything other than numbers, the change is fired even if the textfield content does not change :
<br/>
<input type="text" [(ngModel)]="value" (ngModelChange)="onChange($event)" numbersOnly/>
<br/>
Change fire counter : {{counter}}
<br>
Value = {{value}}
TS file :
(TS文件:)
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
value='';
counter = 0;
onChange(event) {
this.counter = this.counter + 1;
}
}
so see the actual code running please click on : https://stackblitz.com/edit/angular-numbers-only-directive-tb66et
(因此请查看实际运行的代码,请点击: https : //stackblitz.com/edit/angular-numbers-only-directive-tb66et)
PLEASE HELP.
(请帮忙。)
The intention is that the value should not have only number characters. (目的是该值不应仅包含数字字符。)
Regards, Ashish
(问候,Ashish)
ask by Ashish translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…