You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular中实现动态表单控件、数组存值与表格展示?

解决方案

修改 component.ts 实现动态表单与数组存储结果

import { Component, OnInit } from '@angular/core';
import { Quiz1 } from 'src/app/models/quiz1.model';
import { Quiz1Service } from 'src/app/services/quiz1.service';
import { FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-quiz1',
  templateUrl: './quiz1.component.html',
  styleUrls: ['./quiz1.component.css']
})
export class Quiz1Component implements OnInit {

  questions?: Quiz1[];
  answer!: FormGroup;
  userAnswers: { questionId: number; answer: string }[] = [];
  
  constructor(private quiz1Service: Quiz1Service) { }

  ngOnInit(): void {
    this.retrieveQuestions();
  }

  retrieveQuestions(): void {
    this.quiz1Service.getAll()
      .subscribe({
        next: (data: any) => {
          this.questions = data;
          this.buildDynamicForm();
          console.log(data);
        },
        error: (e: any) => console.error(e)
      });
  }

  buildDynamicForm(): void {
    const formControls: { [key: string]: FormControl } = {};
    this.questions?.forEach(question => {
      formControls[`Ans${question.questionId}`] = new FormControl('');
    });
    this.answer = new FormGroup(formControls);
  }

  onSubmit(): void {
    this.userAnswers = [];
    this.questions?.forEach(question => {
      const answerKey = `Ans${question.questionId}`;
      this.userAnswers.push({
        questionId: question.questionId,
        answer: this.answer.value[answerKey] || ''
      });
    });
  }
}

修改 component.html 展示数组内容

<div class="container">
  <form [formGroup]="answer">
    <div *ngFor="let question of questions">
      <span>{{question.questionId}}. {{question.question}}</span><br>
      <input type="radio" formControlName="Ans{{question.questionId}}" value="A" >
      <label>A. {{question.optionsA}}</label><br>

      <input type="radio" formControlName="Ans{{question.questionId}}" value="B" >
      <label>B. {{question.optionsB}}</label><br>

      <input type="radio" formControlName="Ans{{question.questionId}}" value="C" >
      <label>C. {{question.optionsC}}</label><br>

      <input type="radio" formControlName="Ans{{question.questionId}}" value="D" >
      <label>D. {{question.optionsD}}</label><br>
    </div>

    <button class="btn btn-primary" (click)="onSubmit()" type="button">Submit</button>
  </form>

  <div *ngIf="userAnswers.length > 0">
    <table>
      <thead>
        <tr>
          <th>Question No.</th>
          <th>Correct Answer</th>
          <th>Your Answer</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let question of questions; let i = index">
          <td>{{question.questionId}}</td>
          <td>{{question.answer}}</td>
          <td>{{userAnswers[i]?.answer || '未作答'}}</td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

核心改动说明

  • 动态构建表单:拿到题目数据后,遍历每个题目生成对应的FormControl,不再硬编码固定数量的控件,适配任意题目数量。
  • 数组存储答案:用userAnswers数组保存每个题目的ID和用户选择的答案,替代单个变量,结构更灵活。
  • 表格展示关联:遍历题目时通过索引匹配userAnswers中的对应项,确保每个题目展示正确的用户答案,同时处理未作答的情况。

内容的提问来源于stack exchange,提问作者Salahuddin Shayan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 16:50:42