Introduction:
Angular is one of the most powerful and popular JavaScript frameworks for building modern web applications. A calculator application is one of the basic examples of an Angular project that demonstrates its ability to handle calculations and computations.
In this article, we will explore the process of building an Angular calculator application from scratch and provide a step-by-step guide to create a fully functional calculator that performs basic arithmetic operations. We will also explain different Angular features and how they can be utilized to enhance our calculator application.
Prerequisites:
Before we proceed, it’s recommended that you have some basic understanding of Angular, TypeScript, HTML, and CSS. If you are new to Angular, please refer to the official documentation and tutorials to get started.
Getting Started:
To build our Angular calculator, we need to have a basic Angular environment set up on our local machine. We can use the Angular CLI to create a new project by running the following command:
“`
ng new angular-calculator
“`
This will create a new Angular project with all the necessary files and dependencies. Next, we need to generate a new component for our calculator by running the following command:
“`
ng generate component calculator
“`
This will create a new folder named `calculator` inside the `src/app` directory with all the necessary files and boilerplate code.
Let’s begin by opening the `calculator.component.html` file and adding the basic layout of our calculator application.
HTML Layout:
We will use HTML and CSS to structure the layout of our calculator. Here’s the initial HTML code:
“`html
“`
The above code creates a basic calculator interface with a text input that displays the current calculation result and a set of buttons that represent the different functions and numbers present in a calculator.
The `calculator-screen` input field displays the current result of the calculations being performed, and it is marked as disabled to prevent user input.
The `calculator-keys` div contains all the buttons for performing different operations such as addition, subtraction, multiplication, division, etc.
We have added four operator buttons, ten number buttons, a decimal button, an all-clear button, and an equal button.
With the basic layout in place, we can now move to the next step, which is to implement the logic that performs the calculations.
Angular Functionality:
We will use Angular components, services, and directives to manage different aspects of our calculator functionality.
Add the following code to the `calculator.component.ts` file:
“`typescript
import { Component } from ‘@angular/core’;
@Component({
selector: ‘app-calculator’,
templateUrl: ‘./calculator.component.html’,
styleUrls: [‘./calculator.component.css’]
})
export class CalculatorComponent {
currentNumber = ‘0’;
firstOperand = null;
operator = null;
waitingForSecondNumber = false;
public getNumber(v: string) {
console.log(v);
if (this.waitingForSecondNumber) {
this.currentNumber = v;
this.waitingForSecondNumber = false;
} else {
this.currentNumber === ‘0’
? (this.currentNumber = v)
: (this.currentNumber += v);
}
}
public getDecimal() {
if (!this.currentNumber.includes(‘.’)) {
this.currentNumber += ‘.’;
}
}
public clear() {
this.currentNumber = ‘0’;
this.firstOperand = null;
this.operator = null;
this.waitingForSecondNumber = false;
}
public getOperation(op: string) {
console.log(op);
if (this.firstOperand === null) {
this.firstOperand = Number(this.currentNumber);
} else if (this.operator) {
const result = this.calculate();
this.currentNumber = String(result);
this.firstOperand = result;
}
this.operator = op;
this.waitingForSecondNumber = true;
}
public calculate() {
if (this.operator === ‘+’) {
return this.firstOperand + Number(this.currentNumber);
} else if (this.operator === ‘-‘) {
return this.firstOperand – Number(this.currentNumber);
} else if (this.operator === ‘*’) {
return this.firstOperand * Number(this.currentNumber);
} else if (this.operator === ‘/’) {
return this.firstOperand / Number(this.currentNumber);
} else {
return Number(this.currentNumber);
}
}
public getResult() {
if (this.operator === null) {
return;
}
this.currentNumber = String(this.calculate());
this.firstOperand = null;
this.operator = null;
}
}
“`
This code declares a new component with different variables and methods that handle the calculator’s functionality.
The `currentNumber` variable is initialized to 0, which represents the current result of the calculations.
The `firstOperand` variable holds the value of the first operand in the calculation. The `operator` variable holds the value of the operator (+,-,*,/) being used in the calculation.
The `waitingForSecondNumber` flag is used to determine whether the calculator should accept a new number as the second operand or append it to the current one.
The `getNumber()` method is called when a number button is clicked. It appends the number to the current result if the flag is not set, or replaces it entirely if the flag is set.
The `getDecimal()` method allows the insertion of the decimal point in the current number if it is not already present.
The `clear()` method is used to reset the calculator to its initial state by setting all variables to their defaults.
The `getOperation()` method is called when an operator button is clicked. It stores the current number as the first operand if it is the first operation to be performed. If an operator is already present, the calculator performs the calculation using the current number as the second operand and the stored operator and first operand.
The `calculate()` method performs the actual arithmetic calculations based on the operator and operands. If no operator is present, it returns the current number.
Finally, the `getResult()` method is called when the equal button is clicked. It computes the final result of the calculation, stores it in the `currentNumber` variable, and resets all the other variables to their default values.
CSS Styling:
The default Angular project comes with a CSS file that we can use to style our calculator application. We can add the following CSS code to the `calculator.component.css` file to style our calculator:
“`css
.calculator {
width: 220px;
margin: 0 auto;
border: 1px solid #ccc;
border-radius: 5px;
padding: 10px;
}
.calculator-screen {
width: 100%;
font-size: 24px;
height: 60px;
border-radius: 5px;
border: 1px solid #ccc;
margin-bottom: 10px;
text-align: right;
padding-right: 10px;
}
.calculator-keys button {
font-size: 18px;
width: 50px;
height: 50px;
margin: 2px;
background: #dfdfdf;
border: none;
border-radius: 5px;
cursor: pointer;
}
.operator {
background: #f6a732;
color: #fff;
}
.all-clear {
background: #c0392b;
color: #fff;
}
.equal {
background: #1abc9c;
color: #fff;
}
“`
The above CSS code sets the dimensions and styles of the different elements in our calculator application, such as the input field, number, operator, and function buttons.
FAQs:
1. What is Angular?
Angular is a modern JavaScript framework used for building web and mobile applications.
2. What is a calculator application?
A calculator application is a program used for performing mathematical calculations.
3. What features are included in the Angular calculator application?
The Angular calculator application includes features such as the ability to perform arithmetic operations, display the result of the calculation, reset the calculator, and the insertion of decimal points.
4. How can I style my Angular calculator application?
You can style your Angular calculator application using CSS, either by creating a custom stylesheet or modifying the existing one.
5. How can I handle errors or invalid inputs in the calculator?
You can handle errors or invalid inputs by adding conditional statements and checks in the calculator functionality, or by providing feedback to the user.