這裏拼接是我的代碼中,我在打字稿。問題實現一個簡單的計算器這裏,所有的操作,不同的是另外的地方而不是另外做工精細,數字的級聯執行。「+」被執行,而不是另外在AngularJS
HTML代碼:
<input type="text" [(ngModel)]="n1" />
<input type="text" [(ngModel)]="n2" />
<h1>Number 1 : {{n1}}</h1>
<h1>Number 2 : {{n2}}</h1>
<select (change)="handle(selectField.value);" #selectField>
<option value="addition">Addition</option>
<option value="subtraction">Subtraction</option>
<option value="multiply">Multiplication</option>
<option value="divide">Division</option>
</select>
<h1>Result = {{result}}</h1>
我的角度代碼如下:
import {
Component,
OnInit
} from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
n1: number = 0;
n2: number = 0;
result: number = 0;
handle(value: string) {
if (value == "addition") {
this.result = this.n1 + this.n2;
} else if (value == "subtraction") {
this.result = this.n1 - this.n2;
} else if (value == "multiply") {
this.result = this.n1 * this.n2;
} else if (value == "divide") {
this.result = this.n1/this.n2;
}
}
constructor() {}
ngOnInit() {
}
}
我宣佈雙方n1
和n2
數字和也的結果作爲數字。那麼爲什麼這些數字被視爲字符串而不是整數?
注:我已經經歷了類似的問題,其他一些堆棧溢出的職位走了,但沒有找到可行的解決方案。
請幫忙!
,因爲它們都是字符串他們被視爲字符串。我假設你將UI中的一些元素綁定到'n1'和'n2'? – Amy
請注意,TypeScript只執行編譯時類型檢查,而不是運行時。 –
您可以解決它。 this.result =(+ this.n1)+(+ this.n2); – aimprogman