Looking for assistance with my TypeScript code where I've created a basic calculator. Everything is working as expected except for addition, which seems to be concatenating the numbers instead of adding them together.
HTML CODE :
<input type="text" [(ngModel)]="n1" />
<input type="text" [(ngModel)]="n2" />
<h1>Number 1 : {{n1}}</h1>
<h1>Number 2 : {{n2}}</h1>
<select (change)="handle(selectField.value);" #selectField>
<option value="addition">Addition</option>
<option value="subtraction">Subtraction</option>
<option value="multiply">Multiplication</option>
<option value="divide">Division</option>
</select>
<h1>Result = {{result}}</h1>
My Angular Code is as follows:
import {
Component,
OnInit
} from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
n1: number = 0;
n2: number = 0;
result: number = 0;
handle(value: string) {
if (value == "addition") {
this.result = this.n1 + this.n2;
} else if (value == "subtraction") {
this.result = this.n1 - this.n2;
} else if (value == "multiply") {
this.result = this.n1 * this.n2;
} else if (value == "divide") {
this.result = this.n1 / this.n2;
}
}
constructor() {}
ngOnInit() {
}
}
I have defined variables n1
and n2
as numbers in my TypeScript code, along with the result variable. However, it seems that the numbers are being treated as strings rather than integers during operations. Any idea why this might be happening?
Note: I have searched through various posts on Stack Overflow but haven't found a solution yet. Your help would be greatly appreciated!