在Angular 6中传递函数中的参数?

问题描述 投票:0回答:4
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>&nbsp;&nbsp;
  <button value="2" (click)="onClick($event)">2</button>&nbsp;&nbsp;
  <button value="=" (click)="onClick($event)">=</button><br><br>
  Result : {{final}}
</div>

我想在显示功能中打印结果,但它没有这样做。即使在onClick()函数中,if语句中的结果也不是可范围的。我想在显示功能中打印结果

angular typescript event-handling mean-stack
4个回答
0
投票
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;
  }
}

0
投票

尝试更改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


0
投票

您应该在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


0
投票

你的if条件应该是这样的:

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

© www.soinside.com 2019 - 2024. All rights reserved.