Angular FormGroup 忽略我的标准值

斩波器

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

我的表格:

<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());
}

阿米尔

Theinput应该从一个来源获取值,但是您在代码中使用了两个来源:一个是 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,
  });
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章