Issue
I'm trying to display the table based on the input value but when displaying the result I'm getting the last value instead of the entire result as its a for loop.
Here is my multiplytable.component.ts
export class multiplytableComponent implements OnInit{
result!:any;
calcnums =[1,2,3,4,5,6,7,8,9,10,11,12];
calculate(tablenumber:string){
for(let i = 1; i <= 12; i++) {
const result = i * parseFloat(tablenumber);
this.result= `${parseFloat(tablenumber)} * ${i} = ${result}`;
console.log(`${parseFloat(tablenumber)} * ${i} = ${result}`);
}
}
This is my multiplytable.component.html
Enter Table Number: <input type="text" #tablenumber />
<button (click)="calculate(tablenumber.value)">Multiply Table</button>
<h3 *ngFor="let val of calcnums">{{result}}</h3>
This is the output I'm getting
Solution
The for loop should start with zero and end with <
condition as shown in the below condition.
Also we need to loop through the results
array instead of the original array, this is for performance purposes, on button click the values will get set and rendered!
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule],
template: `
Enter Table Number: <input type="text" #tablenumber />
<button (click)="calculate(tablenumber.value)">Multiply Table</button>
<h3 *ngFor="let val of result; let i = index;">
{{val}}</h3>
`,
})
export class App {
result: any = [];
calcnums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
calculate(tablenumber: string) {
this.result = [];
if (tablenumber && +tablenumber !== 0) {
for (let i = 0; i < 12; i++) {
this.result.push(this.getContent(tablenumber, this.calcnums[i]));
}
}
}
getContent(val: any, i: number) {
return `${parseFloat(val)} * ${i} = ${i * parseFloat(val)}`;
}
}
bootstrapApplication(App);
Answered By - Naren Murali
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.