检查一下
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-calculator',
templateUrl: './calculator.component.html',
styleUrls: ['./calculator.component.css']
})
export class CalculatorComponent implements OnInit {
public result:number=0;
public num:number=0;
public final:number=0;
constructor() { }
ngOnInit() {
}
onClick(e){
this.num = Number(e.target.value);
this.result = this.num+this.result;
if(e.target.value == "="){
console.log(this.result); // the output of console here is : null
this.display();
}
}
display(){
console.log(this.result); // here the console output is : NaN
this.final = this.result;
}
}
html
<div>
<input type="number" value="{{result}}"><br><br>
<button value="1" (click)="onClick($event)">1</button>
<button value="2" (click)="onClick($event)">2</button>
<button value="=" (click)="onClick($event)">=</button><br><br>
Result : {{final}}
</div>
我想将结果打印在显示功能中,但没有这样做。即使在onclick()函数中,if语句中的结果也不可划分。我想将结果打印在显示功能
this.num = Number(e.target.value);//Suppose e.target.value is '='
您不能将=
符号转换为数字,否则您将获得NAN
您的代码应如下
onClick(e){
if(e.target.value == "="){
console.log(this.result);
this.display();
}
else{
this.num = Number(e.target.value);
this.result = this.num+this.result;
}
}
尝试更改OnClick方法中的顺序以避免NAN检验。当您尝试将" ="转换为数字时,您将获得NAN。
onClick(e){
if(e.target.value == "="){
console.log(this.result); // the output of console here is : null
this.display();
} else {
this.num = Number(e.target.value);
this.result = this.num+this.result;
}
}
这是一个stackblitz
您应该在OnClick函数中检查if(!isNaN(e.target.value))
。
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
public result:number=0;
public num:number=0;
public final:number=0;
constructor() { }
ngOnInit() {
}
onClick(e){
if(!isNaN(e.target.value)){
this.num = Number(e.target.value);
this.result = this.num+this.result;
}
if(e.target.value == "="){
console.log(this.result); // the output of console here is : null
this.display();
}
}
display(){
console.log(this.result); // here the console output is : NaN
this.final = this.result;
}
}
https://stackblitz.com/edit/angular-add
您是否应该这样的条件:
onClick(e){
if(e.target.value !=='='){
this.num = Number(e.target.value);
this.result = this.num+this.result;
}else{
console.log(this.result);
this.display();
} }
您可以从:stackblitz.com