我正在尝试开发一个具有默认值来自API服务的角5的表单,我只是尝试在初始化formbuilder时分配默认值。如果我使用subscribe()或toPromise(),我得到相同的结果。
Component.ts
settingsForm: any;
constructor(
private userService: UserService,
private settingsService: SettingsService,
private formBuilder: FormBuilder
) { }
ngOnInit() {
this.settingsService.getMetrics$()
.toPromise().then(res =>{
this.settingsForm = this.formBuilder.group({
oee: [res.oee, Validators.required],
fpy: [res.fpy, Validators.required],
difsites: [res.difsites, Validators.required]
});
})
}HTML模板
<form [formGroup]="settingsForm" (ngSubmit)="onSubmit()" style="margin-top: 15px">
<div class="form-group">
<label for="oee">OEE:</label>
<input id="oee" class="form-control" type="text" formControlName="oee">
</div>
<div class="form-group">
<label for="fpy">FPY:</label>
<input id="fpy" class="form-control" type="text" formControlName="fpy">
</div>
<div class="form-group">
<label for="difsites">Diff. Sites:</label>
<input id="difsites" class="form-control" type="text" formControlName="difsites">
</div>
<button type="submit" [disabled]="!settingsForm?.valid" class="btn btn-primary">Save</button>
</form>但就像这样,我收到了一个控制台错误,因为settingsForm是null。
错误: formGroup需要一个FormGroup实例。请给我一张。
发布于 2018-08-01 23:36:28
正如它所定义的那样,在模板呈现时没有定义表单。
最简单的解决方案是用
<form *ngIf="settingsForm" [formGroup]="settingsForm" (ngSubmit)="onSubmit()" style="margin-top: 15px">
看那边的ngIf。
发布于 2018-08-01 23:02:23
之所以会出现这种情况,是因为您没有等待后端的响应来创建指向尚未定义的formGroup的HTML元素。您需要做的是同步创建一个空表单,然后使用setValue方法在后端最终响应时用值更新它。或者,您可以向组件中添加一个布尔值,比如名为loaded的布尔值,这在服务器响应时是正确的,然后在您的html表单上使用*ngIf="loaded"。
https://stackoverflow.com/questions/51642178
复制相似问题