angular - 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());
}
解决方案
应该从一个来源获取值,input
但是您在代码中使用了两个来源:其中一个是 the formControlName
,另一个是value
.
在 Angular Reactive Form 中,您必须保留formControlName
without 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,
});
}
推荐阅读
- sftp - 从 SFTP 文件夹复制和删除文件
- javascript - 如何用“onerror”捕获“ReferenceError”
- powershell - 嵌套 If 语句 first -notlike 条件
- c++ - 检测输入字符串是否有空格
- excel - Excel VBA 438 错误在 PC 上引发,但在 Mac 上没有
- magento2 - 缺少css文件的没有背景的按钮
- transparency - 有没有办法用 Allegro 创建一个半透明的窗口?
- c# - 如何删除 DataGrid 中的选定列?(C#/WPF)
- javascript - 如何检查多个数组上的键值对并使用 javascript 进行过滤?
- algorithm - 前 N 个允许分布式数据的重复算法