top of page

Anguler js - Create a simple calculator using Angular CLI

Step 1: Set up Angular CLI Make sure you have Angular CLI installed on your machine. If not, you can install it globally by running the following command:


npm install -g @angular/cli

Step 2: Create a new Angular project Open your terminal or command prompt and navigate to the directory where you want to create your project. Then, run the following command to create a new Angular project:


ng new calculator-app

Step 3: Navigate to the project directory Change to the project directory by running the following command:


cd calculator-app

Step 4: Generate a new component Generate a new component called calculator by running the following command:


ng generate component calculator

Step 5: Implement the calculator logic Open the calculator.component.ts file located in the src/app/calculator directory and replace its content with the following code:

typescript

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

@Component({
  selector: 'app-calculator',
  templateUrl: './calculator.component.html',
  styleUrls: ['./calculator.component.css']
})
export class CalculatorComponent {
  firstNumber: number;
  secondNumber: number;
  result: number;

  add() {
    this.result = this.firstNumber + this.secondNumber;
  }

  subtract() {
    this.result = this.firstNumber - this.secondNumber;
  }

  multiply() {
    this.result = this.firstNumber * this.secondNumber;
  }

  divide() {
    this.result = this.firstNumber / this.secondNumber;
  }
}

Step 6: Create the calculator template Open the calculator.component.html file located in the src/app/calculator directory and replace its content with the following code:

html

<h2>Calculator</h2>
<div>
<input type="number" [(ngModel)]="firstNumber" placeholder="Enter first number" />
</div>
<div>
<input type="number" [(ngModel)]="secondNumber" placeholder="Enter second number" />
</div>
<div>
<button (click)="add()">Add</button><button (click)="subtract()">Subtract</button><button (click)="multiply()">Multiply</button><button (click)="divide()">Divide</button></div>
<div *ngIf="result !== undefined"><h3>Result: {{ result }}</h3>
</div>

Step 7: Add some basic styling Open the calculator.component.css file located in the src/app/calculator directory and replace its content with the following code:

css

button {
  margin: 5px;
}

Step 8: Run the application Finally, you can run the application by running the following command:


ng serve

Open your browser and navigate to http://localhost:4200/ to see the calculator in action.

That's it! You have created a simple calculator using Angular CLI. You can further enhance the calculator by adding more functionality or improving the user interface.

Related Posts

See All

Comments


bottom of page