簡體   English   中英

Angular ngModel 未正確更新輸入值

[英]Angular ngModel not updating input value correctly

我在嘗試實現智能數字輸入組件時遇到了這個問題,該組件可以設置為允許或禁止負數。 我在<input>元素上有一個(input)事件偵聽器,它運行一個應該將一堆正則表達式模式應用於值的函數。 該函數似乎可以正常工作並且變量的值正在更改,但輸入中的值沒有更新(通過[(ngModel)]綁定到輸入)。

以下是代碼片段(Angular v13.2.4):

//number-input.component.ts
import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-number-input',
  templateUrl: './number-input.component.html',
  styleUrls: ['./number-input.component.scss']
})
export class NumberInputComponent {
  //basic variables
  @Input() inputValue: string | number | null = null;
  @Input() placeholder: string | number | undefined = undefined;

  //allow negative numbers to be used
  @Input('allow-negative') allowNegative: boolean = false; //this is set to false everywhere possible

  //emit the number from the input on change
  @Output('app-change') change = new EventEmitter<number>();

  constructor() { }

  onInput() {
    let str = String(this.inputValue);
    console.log(this.inputValue, str);

    if (!this.allowNegative && str.match(/\-/g)) {
      str = str.replace(/\-/g, '');
    }
    if (this.allowNegative && str.match(/(.+)-/g)) {
      str = str.replace(/(.+)-/g, '$1');
    }
    if (str.match(/[^0-9,\.\-]/g)) {
      str = str.replace(/[^0-9,\.\-]/g, '');
    }
    if (str.match(/,/g)) {
      str = str.replace(/,/g, '.');
    }
    this.inputValue = Number(str);
    console.log(this.inputValue, str);
  }
  onChange() {
    this.change.emit(Number(this.inputValue));
  }
}
<!-- number-input.component.html -->
<input type="text" [(ngModel)]="inputValue" (input)="onInput()" (change)="onChange()">

我測試的案例

輸入值 第一個console.log 第二個console.log 怎么了
123 '123' '123' 123 '123' 沒什么,應該的
123a '123a' '123a' 123 '123' 輸入元素中的值不會更新,但this.inputValue顯然會更新
-123 '-123' '-123' 123 '123' 輸入元素中的值不會更新,但this.inputValue顯然會更新
123-4 '123-4' '123-4' 123 '123' 輸入元素中的值不會更新,但this.inputValue顯然會更新

此外,在輸入元素中的值不更新的所有情況下,輸入任何數字似乎都會更新輸入的值,並且它會正確顯示。 輸入任何其他字符都不起作用。

有任何想法嗎?

編輯

我想出了一個不涉及ngModel的解決方案:

onInput()方法現在接受一個事件參數,我用它來直接編輯輸入元素的值。 這是最終工作的代碼:

onInput(event: Event) {
  let inputEl = event.target as HTMLInputElement;
  let str = String(inputEl.value);

  // some regex matches here

  this.inputValue = Number(str);
  inputEl.value = str;
}

您可以將數據傳遞給 $event 對象:

<input type="text" [(ngModel)]="inputValue" (input)="onInput($event)" >

在 ts 文件上:

  onInput(event:any) {
    let str = String(event.target.value);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM