You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 7计算器开发问题:点击等号无法正确输出计算结果

Fixing Your Angular 7 Calculator Issues

Hey there, let's work through the problems with your calculator and get it working correctly! I've spotted a couple of key issues in your code, plus some small tweaks needed for proper Angular behavior.

Core Problems Identified

  • Incorrect Operator Comparison: In your onSelectEqual method, you're using the assignment operator = instead of a comparison operator (=== or ==). This means you're always setting selectedOperator to '+' instead of checking its value—explaining why only addition seems to work, and why the operator gets changed when you click equals.
  • String Concatenation Instead of Numeric Calculation: Your num1 and num2 are stored as strings, so using + just concatenates them (e.g., "2" + "3" becomes "23" instead of 5). You need to convert these strings to numbers first before doing calculations.
  • Angular Syntax Mistakes: You're using AngularJS directives like ng-model and ng-init which don't work in Angular 7+. Angular uses [(ngModel)] for two-way binding, and ng-init isn't needed here since your click handlers already set the operator.

Corrected Code

calculator.component.html

<div class="calculator">
  <h1>Calculator</h1>
  <div>
    <input [(ngModel)]="num1" type="text" placeholder="Enter value">
    <p><span><input type="text" readonly [value]="selectedOperator"></span></p>
    <p>
      <input class="num2" [(ngModel)]="num2" type="text" placeholder="Enter value">
      <button class="result" (click)="onSelectEqual()">=</button>
      <span><input type="text" readonly [value]="answer"></span>
    </p>
    <button class="operator" (click)="onSelectAdd()">+</button>
    <button class="operator" (click)="onSelectMinus()">-</button>
    <button class="operator" (click)="onSelectTimes()">*</button>
    <button class="operator" (click)="onSelectDivide()">/</button>
  </div>
</div>

calculator.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-calculator',
  templateUrl: './calculator.component.html',
  styleUrls: ['./calculator.component.css']
})
export class CalculatorComponent implements OnInit {
  selectedOperator = '';
  num1 = '';
  num2 = '';
  answer = '';

  constructor() { }

  ngOnInit(): void {
  }

  onSelectAdd() {
    this.selectedOperator = '+';
  }

  onSelectMinus() {
    this.selectedOperator = '-';
  }

  onSelectTimes() {
    this.selectedOperator = '*';
  }

  onSelectDivide() {
    this.selectedOperator = '/';
  }

  onSelectEqual() {
    // Convert string inputs to numbers
    const number1 = Number(this.num1);
    const number2 = Number(this.num2);

    // Use strict comparison (===) for operator check
    switch(this.selectedOperator) {
      case '+':
        this.answer = (number1 + number2).toString();
        break;
      case '-':
        this.answer = (number1 - number2).toString();
        break;
      case '*':
        this.answer = (number1 * number2).toString();
        break;
      case '/':
        // Add a check to avoid division by zero
        if (number2 !== 0) {
          this.answer = (number1 / number2).toString();
        } else {
          this.answer = 'Error';
        }
        break;
      default:
        this.answer = 'Select operator';
    }
  }
}

Additional Notes

  • Don't forget to import FormsModule in your AppModule (or the module containing your calculator component) to use [(ngModel)]:
    import { FormsModule } from '@angular/forms';
    
    @NgModule({
      imports: [
        // ... other imports
        FormsModule
      ]
    })
    export class AppModule { }
    
  • I replaced the if-else chain with a switch statement for cleaner operator handling, and added a division-by-zero check to avoid unexpected results.

内容的提问来源于stack exchange,提问作者LJ27

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 18:02:50