changhuixu / ngx-digit-only

An Angular directive to only allow [0-9] in the input box when typing, pasting or drag/dropping.

Home Page:https://changhuixu.github.io/ngx-digit-only/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Can't disable paste

plmpradeep opened this issue · comments

I want to disable paste. But using (paste)="false" with digitOnly directive doesn't work.

   <input [(ngModel)]="test" placeholder="Enter Value" type="text" digitOnly
                         [pattern]="getInputPattern()" (input)="onInputChange()" (paste)="false">

That did not work for me either, nor did onPaste="return false;" nor trying event.preventDefault(); as suggested here.

The following did work. It allows you to specify allowPaste=false on the input control.

add this

@input() allowPaste = true;

and then modify the onPaste as follows

@HostListener('paste', ['$event'])
onPaste(event: any): void {
if (this.allowPaste === true) {
let pastedInput: string = '';
if ((window as { [key: string]: any })['clipboardData']) {
// Browser is IE
pastedInput = (window as { [key: string]: any })['clipboardData'].getData(
'text'
);
} else if (event.clipboardData && event.clipboardData.getData) {
// Other browsers
pastedInput = event.clipboardData.getData('text/plain');
}

  this.pasteData(pastedInput);
  event.preventDefault();
} else {  // this prevents the paste 
  event.preventDefault();
  event.stopPropagation();
}

}

Hi @billn6 , I think your solution works.

@plmpradeep , what's your opinion on this one (adding a new input field to control the paste handler)?

Yup. Suggested changes work fine.

@changhuixu Will you throw a small but needed change into the 2.x branch as well?

Hi @patrykdawid
A v2.4.0 is released. Thank you.