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

Angular12中多个FormGroup调用patchValue仅部分表单填充成功如何解决

问题原因

  1. 接口字段取值路径错误:API返回的licence_number字段是嵌套在employee.licences数组的子对象中,不是employee的直接属性,你当前的接口定义和取值逻辑都写错了路径,导致取到的值是undefined。
  2. HTML结构嵌套错误:你当前把证照表单的div写在了个人资料表单的div内部,而个人资料表单的父div绑定了*ngIf="profileTemplate",当你点击切换到证照页时profileTemplate为false,整个父div被销毁,证照表单根本不会渲染,自然看不到回填的值。

解决步骤

  1. 修正TypeScript接口定义
// 新增证照类型定义
export interface ILicence {
  id: number;
  licence_number: string;
}

export interface IEmployee {
  id?: number;
  first_name: string;
  other_name: string;
  last_name: string;
  licences: ILicence[]; // 替换原有的licence_number字段
}
  1. 修正表单回填逻辑
    修改loadEmployeeById方法中证照表单的取值逻辑,同时增加空判断避免数组为空时报错:
loadEmployeeById() {
 this.employeeService.getEmployeeById(this._id)
 .subscribe(
  (data: EmployeeResponse) => {
    this.employee = data.results.employee;
    // 个人资料表单回填不变
    this.profileInfoForm.patchValue({
      first_name: this.employee.first_name,
      other_name: this.employee.other_name,
      last_name: this.employee.last_name,
    });
    // 修正证照表单取值
    const firstLicence = this.employee.licences?.[0];
    this.licenceInfoForm.patchValue({
      id: firstLicence?.id ?? '',
      licence_number: firstLicence?.licence_number ?? ''
    });
  }
 );
}
  1. 修正HTML嵌套结构
    把证照表单的div从个人资料表单的div中移出来,改为平级关系,同时移除按钮上重复的class属性:
<div class="col-md-9" *ngIf="employee != undefined">
  <!-- 个人资料表单 独立div -->
  <div *ngIf="profileTemplate" class="card card-default color-palette-box">
    <div class="card-body">
      <form [formGroup]="profileInfoForm" (ngSubmit)="onSubmitProfile()">
        <!-- 原有个人资料表单代码不变 -->
        <div class="card-footer">
          <button type="submit" class="btn btn-success" [disabled]="isLoading" (click)="profileValidate()">
            <span *ngIf="isLoading" class="spinner-border spinner-border-sm mr-1"></span>
            <i class="fa fa-save" aria-hidden="true"></i> Save
          </button>
        </div>
      </form>
    </div>
  </div>

  <!-- 证照表单 独立div,和上面的个人资料div平级 -->
  <div *ngIf="licenceTemplate" class="card card-default color-palette-box">
    <form [formGroup]="licenceInfoForm" (ngSubmit)="onSubmitLicence()">
      <!-- 原有证照表单代码不变 -->
      <div class="card-footer">
        <button type="submit" class="btn btn-success" [disabled]="isLoading" (click)="licenceValidate()">
          <span *ngIf="isLoading" class="spinner-border spinner-border-sm mr-1"></span>
          <i class="fa fa-save" aria-hidden="true"></i> Save
        </button>
      </div>
    </form>
  </div>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 14:21:03