How do I restrict an input to only accept numbers?

前端 未结 17 1230
感情败类
感情败类 2020-12-07 09:28

I am using ngChange in AngularJS to trigger a custom function that will remove any letters the user adds to the input.



        
17条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-07 10:01

    SOLUTION: I make a directive for all inputs, number, text, or any, in the app, so you can input a value and change the event. Make for angular 6

     import { Directive, ElementRef, HostListener, Input } from '@angular/core';
    
     @Directive({
    // tslint:disable-next-line:directive-selector
    selector: 'input[inputType]'
    })
      export class InputTypeDirective {
     constructor(private _el: ElementRef) {}
    
     @Input() inputType: string;
     // tipos: number, letter, cuit, tel
    
    @HostListener('input', ['$event']) onInputChange(event) {
    if (!event.data) {
      return;
    }
    
    switch (this.inputType) {
      case 'number': {
        const initalValue = this._el.nativeElement.value;
        this._el.nativeElement.value = initalValue.replace(/[^0-9]*/g, '');
        if (initalValue !== this._el.nativeElement.value) {
          event.stopPropagation();
        }
         break;
              }
           case 'text': {
            const result = event.data.match(/[^a-zA-Z Ññ]*/g);
            if (result[0] !== '') {
               const initalValue = this._el.nativeElement.value;
               this._el.nativeElement.value = initalValue.replace(
              /[^a-zA-Z Ññ]*/g,
               ''
             );
               event.stopPropagation();
            }
            break;
        }
            case 'tel':
              case 'cuit': {
             const initalValue = this._el.nativeElement.value;
          this._el.nativeElement.value = initalValue.replace(/[^0-9-]*/g, '');
           if (initalValue !== this._el.nativeElement.value) {
             event.stopPropagation();
           }
         }
       }
      }
       }
    

    HTML

         
    

提交回复
热议问题