简体   繁体   中英

Unable Trim value of a textBox using ngModel and directive

I am trying to trim a text input but it is duplicating the value在此处输入图像描述

I am new to angular can you please help me out finding the solution StackBlitz Code

preventDefault() Usage:

The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.

The problem was here, that you are trying to stop the pasting behavior.

if (!Number(event)) {
  e.preventDefault();
}

Scenarios:

Scenario 1: Pasted value is not a number

  • It will block the pasting behavior.

Scenario 2: Pasted value is a number

  • From the above code, it will not block the pasting behavior.
  • And next you are assigning the value to the <input> element.
  • Thus you will see the number will be duplicated.

I believe what you try to achieve:

  1. Blocking the default pasting behavior.

  2. Only allow the number to be pasted. When the value is not a number, it will exit the function.

if (!Number(event)) return;

The complete code of the "paste" listener should be as below:

@HostListener('paste', ['$event']) onPaste(e: ClipboardEvent) {
  e.preventDefault();

  let event = e.clipboardData.getData('text');

  let reg = new RegExp(/\s/g);
  //allow paste only number values
  if (!Number(event)) return;

  if (reg.test(event)) {
    console.log('Dir "' + event + '"');

    this.eleRef.nativeElement.value = event.trim();
  }
}

Demo @ StackBlitz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM