Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Table multiplication in Angular using ngFor

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
enter image description here

>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);

stackblitz

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading