首页 > 解决方案 > Angular FormGroup 忽略了我的标准值

问题描述

我的表单中已经有一些来自我的 web api 的标准值。问题是我的 FromGroup 忽略了它们并将所有值设置为空。仅当我自己在输入中键入内容时,值才不是空的。因此,如果我尝试更新用户,它将重置整个用户。

我的表格:

<form [formGroup]="persoForm" (ngSubmit)="onSubmit()">

            <div id="firma">
                <mat-form-field appearance="standard" id="firm" floatLabel="always">
                    <mat-label> Firmenbez.:</mat-label>
                    <input matInput type="text" name="firm" formControlName="firmenBez" [value]="person.firmenbezeichnung"/>
                </mat-form-field>
            </div>
</form> 

TS

persoForm = new FormGroup({
    firmenBez: new FormControl(),
  })

onSubmit(){ //currently only there to check if the values are still null
      
      console.log(this.persoForm.getRawValue());
}

标签: angulartypescriptangular-forms

解决方案


应该从一个来源获取值,input但是您在代码中使用了两个来源:其中一个是 the formControlName,另一个是value.

在 Angular Reactive Form 中,您必须保留formControlNamewithout value,并根据您的 API 数据处理其值:

  • 如果您在初始化之前获取数据FormGroup,那么您必须像下面这样初始化它:
// init the form-group when you get the data from the API like the following:
this.personForm = new FormGroup({
  firmenBez: new FormControl(this.person.firmenbezeichnung),
});
  • 但是如果你在初始化之后得到日期FormGroup,你可以保持你的初始化不变,然后补丁数据来自API,如下所示:
onDataReceived(person) {
  this.personForm.patchValue({
    firmenBez: person.firmenbezeichnung,
  });
}

推荐阅读