如何从HTML表格每行的单选按钮获取值到TypeScript(Angular)
解决Angular表格每行单选按钮取值传递问题
核心问题修正
你的代码存在两个关键问题:
- 所有行的单选组复用了同一个
formControlName,无法区分各行的选择值 - TypeScript中表单数组的初始化语法错误,未正确映射每行的技能ID与评分
修改后的TypeScript代码
import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, FormArray } from '@angular/forms'; export class FeedbackFormComponent implements OnInit { feedbackForm!: FormGroup; skills: any[] = []; ratings: any[] = []; constructor( private fb: FormBuilder, private ratingService: RatingService, private skillService: SkillService, private resFeedbackService: ResFeedbackService ) {} ngOnInit(): void { this.ratings = this.ratingService.getAllRatings(); this.skills = this.skillService.getAllSkills(); // 初始化表单,动态创建对应技能数量的FormArray this.feedbackForm = this.fb.group({ applicantId: [''], positionId: [''], comments: [''], recommendation: [''], resourceRating: this.fb.array( this.skills.map(skill => this.fb.group({ skillId: [skill.skillId], // 绑定当前技能的ID ratingId: [''] // 存储当前技能的评分值 }) ) ) }); } // 便捷获取resourceRating表单数组的方法 get resourceRatingArray(): FormArray { return this.feedbackForm.get('resourceRating') as FormArray; } submitData(){ console.log('表单数据:', this.feedbackForm.value); this.resFeedbackService.createResourceFeedback(this.feedbackForm.value); } }
修改后的HTML代码
<form [formGroup]="feedbackForm" (ngSubmit)="submitData()"> <table class="res-tbl"> <thead style="background-color: #f6f9fc;"> <tr> <th class="table-head">技能名称</th> <th class="table-head">评分</th> </tr> </thead> <tbody formArrayName="resourceRating"> <tr class="skill-tr" *ngFor="let skillGroup of resourceRatingArray.controls; let i = index;" [formGroupName]="i"> <td class="skill-td"> <b>{{skills[i].skillName}}<span>:</span></b>{{skills[i].description}} </td> <td> <mat-radio-group formControlName="ratingId" name="ratingId{{i}}"> <span class="radio-span">0</span><mat-radio-button class="radio-btn" value="0"></mat-radio-button> <span class="radio-span">1</span><mat-radio-button class="radio-btn" value="1"></mat-radio-button> <span class="radio-span">2</span><mat-radio-button class="radio-btn" value="2"></mat-radio-button> <span class="radio-span">3</span><mat-radio-button class="radio-btn" value="3"></mat-radio-button> <span class="radio-span">4</span><mat-radio-button class="radio-btn" value="4"></mat-radio-button> </mat-radio-group> </td> </tr> </tbody> </table> <button type="submit">Submit</button> </form>
关键修改说明
- 表单数组初始化:通过
this.skills.map遍历技能列表,为每个技能创建包含skillId和ratingId的FormGroup,确保每行数据与技能一一对应 - 表单数组绑定:在
<tbody>上添加formArrayName="resourceRating",循环时用[formGroupName]="i"绑定数组中的对应FormGroup - 单选组绑定:将
mat-radio-group的formControlName改为ratingId,对应FormGroup中的评分控件 - 技能ID绑定:初始化FormGroup时自动填充当前技能的
skillId,提交时可以直接获取每个技能对应的评分
提交表单后,this.feedbackForm.value会输出类似以下结构的数据:
{ "applicantId": "", "positionId": "", "comments": "", "recommendation": "", "resourceRating": [ { "skillId": "skill_1", "ratingId": "3" }, { "skillId": "skill_2", "ratingId": "1" } ] }
内容的提问来源于stack exchange,提问作者Rose
相关产品推荐
相关产品推荐

