-1

I have an input type number. I have a directive that successfully blocks characters other than numbers. And this also allows only single decimal point.

What I need is, the directive should allow copy from field and paste into the field as well.

<input type="number" appNumbersOnly />
import { Directive, ElementRef, HostListener } from "@angular/core";

@Directive({
    selector: '[appNumbersOnly]'
  })
export class NumbersOnlyDirective {
    public text;
    private regex: RegExp = new RegExp(/^-?[0-9]+(\.[0-9]*){0,1}$/g);
    private specialKeys: Array<string> = ['Backspace', 'Tab'];

    constructor(private el: ElementRef) {}
    @HostListener('keypress', ['$event']) onKeyDown(event: KeyboardEvent) {
      if (this.specialKeys.indexOf(event.key) !== -1) return;

      const current: string = this.el.nativeElement.value;
      const next: string = current.concat(event.key);

      if(next.includes('.')){
        if(this.text == next) event.preventDefault();
        this.text= next;
      }
      if ((next && !String(next).match(this.regex))) {  
        event.preventDefault();
      }
    }
  }

How to make this directive allow copy paste?

  • Have you tried using 'change' instead of 'keypress' ? – skolldev Aug 16 '19 at 07:12
  • Welcome to SO! Please follow the guidelines https://stackoverflow.com/help/how-to-ask to avoid getting downvoted. It is good that you tried yourself, but edit your question so that you explain further the context and why you did, what you did. – B--rian Aug 16 '19 at 07:32
  • @xdecdec 'change' event and 'input' event are triggered after "type="text"" modifies the inut value. For example, if I type double dot(..), "type="text"" makes the value of input as blank('') internally. So, the event triggered by 'change' or 'input' will have '' as value. – Athreya M R Bhatt Aug 22 '19 at 08:39

1 Answers1

1

I am not sure about your requirenment. But I think this can help you.

copy Angular 5 - Copy to clipboard

Paste Angular - On Paste Event Get Content