我對 Angular 有點熟悉,剛剛進入 Ionic 框架。
我面臨一個問題。我正在嘗試計算(求和)單獨輸入欄位中給出的兩個數字并在下面顯示結果。如果我輸入以下數字,計算將按預期作業:1 或 1.0 但輸入 1。(點后沒有給出數字)為該輸入欄位回傳 null。
在模板中,我的代碼如下:
<b>1st input</b> <ion-input type="number" (ionChange)="calculate()" [(ngModel)]="firstInput"></ion-input>
<b>2nd input</b> <ion-input type="number" (ionChange)="calculate()" [(ngModel)]="secondInput"></ion-input>
<b>Total:</b> {{ total }}
在組件中:
firstInput = null;
secondInput = null;
total = null;
...
calculate() {
this.total = this.firstInput this.secondInput;
}
為什么為 1 回傳 null。?是否有將 1. 轉換為數字的解決方法?
uj5u.com熱心網友回復:
如果您使用沒有 type="number" 的普通輸入并在計算函式中使用Number()轉換值,您將得到正確的結果:
<b>1st input</b> <input [(ngModel)]="firstInput" />
<b>2nd input</b> <input [(ngModel)]="secondInput" />
<button (click)="calculate()"></button>
<b>Total:</b> {{ total }}
firstInput = null;
secondInput = null;
total: number | null = null;
calculate() {
this.total = Number(this.firstInput) Number(this.secondInput);
}
uj5u.com熱心網友回復:
更改您必須的 {total} 而只是說 {input1 input 2} 并確保它們是數字型別,否則只需將它們轉換為一個
{數字(輸入1) 數字(輸入2)}
uj5u.com熱心網友回復:
感謝您的回復,抱歉耽擱了,不能早點發帖。
但是,我意識到將欄位鍵入為數字欄位會剝奪我實作所需的自由。所以我最終只使用常規的離子輸入,而不是把它作為數字輸入,而是給它一個十進制的輸入模式,所以當輸入聚焦時,移動設備會顯示數字鍵盤。
模板:
<b>1st input</b> <ion-input #firstInputRef (ionChange)="handleFirstInput(firstInputRef)" inputmode="decimal" [(ngModel)]="firstInput"></ion-input>
<b>2nd input</b> <ion-input #secondInputRef (ionChange)="handleSecondInput(secondInputRef)" inputmode="decimal" [(ngModel)]="secondInput"></ion-input>
<b>Total:</b> {{ total }}
零件:
@ViewChild('firstInputRef', {static: false, read: ElementRef}) firstInputRef: ElementRef;
@ViewChild('secondInputRef', {static: false, read: ElementRef}) secondInputRef: ElementRef;
readonly twoDotsRegex = /(\..*){2,}/;
...
handleFirstInput(input) {
// Get the caret position
const caretPosition = this.firstInputRef.nativeElement.querySelector('input').selectionStart;
if (this.twoDotsRegex.test(input.value)) {
// If second dot (.) is given, let's remove the added character
input.value = input.value.substring(0, caretPosition - 1) input.value.substring(caretPosition, input.value.length);
}
this.firstInput = input.value;
this.calculate();
}
handleSecondInput(input) {
// Get the caret position
const caretPosition = this.secondInputRef.nativeElement.querySelector('input').selectionStart;
if (this.twoDotsRegex.test(input.value)) {
// If second dot (.) is given, let's remove the added character
input.value = input.value.substring(0, caretPosition - 1) input.value.substring(caretPosition, input.value.length);
}
this.secondInput = input.value;
this.calculate();
}
...和原始帖子中的計算方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/480721.html
