使用 ngFor 在 Angular 中进行表乘法

问题描述 投票:0回答:1

我试图根据输入值显示表格,但在显示结果时,我得到的是最后一个值,而不是整个结果作为 for 循环。

这是我的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}`);
  }
  }

这是我的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>

这是我得到的输出

angular multiplication ngfor
1个回答
1
投票

for 循环应从零开始并以

<
条件结束,如下面的条件所示。

我们还需要循环遍历

results
数组而不是原始数组,这是出于性能目的,单击按钮时将设置并渲染值!

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 = [];
    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);

堆栈闪电战

© www.soinside.com 2019 - 2024. All rights reserved.