1. Create a new Angular application using the command ng new calculator-app
. This will create a new directory with the basic file structure for an Angular application.
2. In the src/app
directory, create a new component for the calculator using the command ng generate component calculator
.
3. In the calculator.component.html
file, you can create the HTML template for the calculator.
<form> <input type="text" [(ngModel)]="num1" name="num1" placeholder="Number 1"> <br> <input type="text" [(ngModel)]="num2" name="num2" placeholder="Number 2"> <br> <select [(ngModel)]="operator" name="operator"> <option value="">None</option> <option value="add">Add</option> <option value="subtract">Subtract</option> <option value="multiply">Multiply</option> <option value="divide">Divide</option> </select> <br><br> <button type="button" (click)="calculate()">Calculate</button> </form> <p *ngIf="result">The answer is: {{ result }}</p>
4. In the calculator.component.ts file, you can define the component’s class and the logic for the calculator.
import { Component } from '@angular/core'; @Component({ selector: 'app-calculator', templateUrl: './calculator.component.html', styleUrls: ['./calculator.component.css'] }) export class CalculatorComponent { num1: number; num2: number; operator = ''; result: number; calculate() { switch (this.operator) { case 'add': this.result = this.num1 + this.num2; break; case 'subtract': this.result = this.num1 - this.num2; break; case 'multiply': this.result = this.num1 * this.num2; break; case 'divide': if (this.num2 !== 0) { this.result = this.num1 / this.num2; } else { this.result = null; alert('Cannot divide by zero!'); } break; default: alert('You need to select a method!'); break; } } }
5. In the app.module.ts file, you will need to import the FormsModule to use the two-way data binding syntax with ngModel.
import { FormsModule } from '@angular/forms'; @NgModule({ imports: [ FormsModule ], ... }) export class AppModule { }
6. Finally, in the app.component.html file, you need to add the <app-calculator> tag to display the calculator.