Skip to main content

Angular: building basic calculator

Introduction

In this tutorial, we will walk through the steps to create a simple calculator application using Angular. This exercise is designed to help you practice your Angular skills and understand the basics of building a user interface and handling events.

Prerequisites

Before you begin, ensure you have the following:
  • Basic understanding of Angular
  • Angular CLI installed
  • Node.js and npm installed

Step 1: Setting Up the Project

First, let's create a new Angular project. Open your terminal and run:
  • ng new BasicCalculator 
  • cd BasicCalculator 
  • ng serve
This will set up a new Angular project and start the development server. You can view the default application by navigating to http://localhost:4200 in your browser.

Step 2: Designing the Calculator UI

In app.component.html, design the UI of the calculator. Here's a simple structure to get you started:

<div class="container">
  <div class="calculator">
    <div><input class="display" id="display" [(ngModel)]="result"></div>
    <div class="row">
      <button class="btn btn-secondary col-3" (click)="inputNumber(7)">7</button>
      <button class="btn btn-secondary col-3" (click)="inputNumber(8)">8</button>
      <button class="btn btn-secondary col-3" (click)="inputNumber(9)">9</button>
      <button class="btn btn-warning col-3" (click)="inputOperator('/')">/</button>
    </div>
    <div class="row">
      <button class="btn btn-secondary col-3" (click)="inputNumber(4)">4</button>
      <button class="btn btn-secondary col-3" (click)="inputNumber(5)">5</button>
      <button class="btn btn-secondary col-3" (click)="inputNumber(6)">6</button>
      <button class="btn btn-warning col-3" (click)="inputOperator('*')">*</button>
    </div>
    <div class="row">
      <button class="btn btn-secondary col-3" (click)="inputNumber(1)">1</button>
      <button class="btn btn-secondary col-3" (click)="inputNumber(2)">2</button>
      <button class="btn btn-secondary col-3" (click)="inputNumber(3)">3</button>
      <button class="btn btn-warning col-3" (click)="inputOperator('-')">-</button>
    </div>
    <div class="row">
      <button class="btn btn-secondary col-3" (click)="inputNumber(0)">0</button>
      <button class="btn btn-secondary col-3" (click)="inputDecimal('.')">.</button>
      <button class="btn btn-success col-6" (click)="calculate()">=</button>
      <button class="btn btn-warning col-3" (click)="inputOperator('+')">+</button>
    </div>
    <div class="row">
      <button class="btn btn-danger col-12" (click)="clear()">C</button>
    </div>
  </div>
</div>

Step 3: Adding Functionality

In app.component.ts, add the logic for handling button clicks and performing calculations:


	inputNumber(number: number) {
      if (this.result == "0")
        this.result = "";

      this.result = this.result.concat(number.toString());
    }

	inputOperator(operator: string) {
      if (this.result.lastIndexOf(".") > -1)
        this.result = this.result.concat("00");

      if (this.result != "") {
        this.array.push(this.result);
        this.array.push(operator);
        this.result = "";
      }

      let lastValue = this.array[this.array.length - 1];
      console.log(lastValue);

      if (lastValue == "/")
        this.ReInputOperator(this.array, operator);
      if (lastValue == "+")
        this.ReInputOperator(this.array, operator);
      if (lastValue == "-")
        this.ReInputOperator(this.array, operator);
      if (lastValue == "*")
        this.ReInputOperator(this.array, operator);
    }
    
    calculate() {
      if (this.result != "")
        this.array.push(this.result);

      this.result = evaluate(this.array.join(" "));
    }

Step 4: Styling the Calculator

In calculator.component.css, add some basic styles to make the calculator look better:

<style>
  .calculator {
    margin: 50px auto;
    padding: 20px;
    width: 320px;
    background: #f7f7f7;
    border-radius: 10px;
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2);
  }
  .calculator .display {
    height: 60px;
    width: 270px;
    margin-bottom: 10px;
    text-align: right;
    font-size: 24px;
    line-height: 60px;
    background: #333;
    color: #fff;
    padding: 0 20px;
    border-radius: 5px;
  }
  .calculator .btn {
    width: 60px;
    height: 60px;
    font-size: 24px;
    margin: 5px;
  }
</style>

Step 5: Testing the Calculator

Run the application and test the calculator to ensure it works as expected. Navigate to http://localhost:4200 and use the calculator.

Screenshot









Conclusion

In this tutorial, we built a basic calculator using Angular. This exercise helped us practice component creation, event handling, and basic styling. Feel free to expand on this project by adding more features or improving the design.

Code Repository

You can find the source code for this project on my GitHub repository.

Comments

Popular posts from this blog

Car Wash System vb.net

This software consists of a database that save the registration number of every vehicle being wash along side with the date, type of wash made and price Screen Shot Source Code To view records in the database: Dim conn As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\washRcd.accdb;Persist Security Info=False") Dim sql As String sql = " SELECT * FROM tblwash" conn.Open() Dim dt As New DataTable Dim cmd2 As New OleDb.OleDbDataAdapter(sql, conn) cmd2.Fill(dt) DataGridView1.DataSource = dt DataGridView1.Refresh() conn.Close() To insert new record in the database: Private Sub insert() Dim conn As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\washRcd.accdb;Persist Security Info=False") Dim updateSql As String = String.Format(...

Face recognition using EmguCV 3.0 and typing pattern recognition

Introduction An MSc project with the title Student Examination System, where the objective is to put the students in an examination condition but instead of having an invigilator in an examination center, the system will cater for the proper ongoing of the exam. the system can be used as an online examination system The system is able to: Recognizing the face shape of a particular student Detect if there is more than one person in the examination room  Analyze the typing pattern of a student and detect if any one person is taking part in the exam voice recognition for the student and detect if there is more than one person speaking in the examination room Setup Download Emgu CV from  http://www.emgu.com/wiki/index.php/Main_Page Download Haarcascade from  https://github.com/opencv/opencv/tree/master/data/haarcascades Create an account at  https://www.keytrac.net/ Face recognition The snippet below illustrates how the Emgu CV is loaded whe...

Student Information System - AngularJS , ASP.NET API, C#

Web based application the student information system is a small application that allows user to register and login to view information about a particular student and can perform several actions like Login and register to the application View students  Add new student Delete a particular student Update user information Screen Shot Project architecture routing.js, config.js and app.js allow the application to route from one partial view to another and config.js is used to save all the endpoint needed to access the API.   For separation of concerns, in the solution panel separate partial views, controller and services in different directories and reference it in index.html to enable angular to load all the files required Login process login.html LoginController.js Using $resource from AngularJS to make an API call and response  with a user details model UserViewModel and UserDetailsViewModel Using Unity fo...