2017-06-21 29 views
0

這裏拼接是我的代碼中,我在打字稿。問題實現一個簡單的計算器這裏,所有的操作,不同的是另外的地方而不是另外做工精細,數字的級聯執行。「+」被執行,而不是另外在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() { 

    } 

} 

我宣佈雙方n1n2數字和也的結果作爲數字。那麼爲什麼這些數字被視爲字符串而不是整數?

注:我已經經歷了類似的問題,其他一些堆棧溢出的職位走了,但沒有找到可行的解決方案。

請幫忙!

+4

,因爲它們都是字符串他們被視爲字符串。我假設你將UI中的一些元素綁定到'n1'和'n2'? – Amy

+3

請注意,TypeScript只執行編譯時類型檢查,而不是運行時。 –

+1

您可以解決它。 this.result =(+ this.n1)+(+ this.n2); – aimprogman

回答

1

你可以解決它。 this.result =(+ this.n1)+(+ this.n2);

+3

雖然這個代碼片斷可以解決問題,[包括解釋](// meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)確實有助於提高您的帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。也請儘量不要用解釋性註釋來擠佔代碼,這會降低代碼和解釋的可讀性! –

1

從HTML輸入任何值自動是字符串。要解決此問題,您必須將您的輸入值轉換/轉換爲數字。 (+ this.n1)破解它,但要真正做到這一點,你應該施放或轉換你的值。

this.result = parseInt(this.n1) + parseInt(this.n2); 

這只是一種方式。還有其他幾個。

+1

我還應該注意,如果輸入的值計算爲NAN,則此方法很容易失敗。 – MBielski