typescript - Angular FormGroup 忽略了我的标准值
我的表单中已经有一些来自我的网络 API 的标准值。问题是我的 FormGroup 忽略了它们,并将所有值设置为 null。只有当我自己在输入框中键入内容时,值才不会是 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());
}答案#1
input 应该只从一个来源获取值,但你在代码中使用了两个来源:其中一个是 formControlName,另一个是 value。
在 Angular 响应式表单中,你必须保持 formControlName 不带 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,
});
}
