P
P
prolina2019-12-12 10:55:26
Angular
prolina, 2019-12-12 10:55:26

Entering only numbers?

@Directive({
  selector: '[numbersOnly]'
})
export class OnlyNumberDirective {

  constructor(private _el: ElementRef) { }

  @HostListener('input', ['$event']) onInputChange(event) {
    const initialValue = this._el.nativeElement.value;

    this._el.nativeElement.value = initialValue.replace(/[^0-9]*/g, '');
    if ( initialValue !== this._el.nativeElement.value) {
      event.stopPropagation();
    }
  }
}

There is this directive that makes it possible to enter only numbers in the field. But, if the length is set for the field and start entering the letter first, then the length will already become equal to one (but the letter will not be visible in the input), then if you enter a number, then the length is still one. Also, if there is a field with number of characters = maximum length, then remove one character and add a letter, then the field will be valid. How can this problem be solved?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shvets, 2019-12-12
@Xuxicheta

import { Directive } from '@angular/core';
import { NgControl } from '@angular/forms';
import { Subscription } from 'rxjs';

@Directive({
  selector: '[numbers]',
})
export class NumbersDirective  {
  sub = new Subscription();

  constructor(
    private ngControl: NgControl
  ) { }

  ngOnInit() {
    this.sub = this.ngControl.valueChanges.subscribe(value => {
      this.ngControl.control.setValue(
        (value || '').replace(/[^0-9]*/g, ''),
        { emitEvent: false },
      )
    });
  }
  ngOnDestroy() {
    this.sub.unsubscribe();
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question