Angular 5 组 FormBuilder,填充来自 Observable 或 Promise 的默认值

Angular 5 group FormBuilder with filling default values from Observable or Promise

我正在尝试在 angular 5 中开发一个表单,其默认值来自 API 服务 我只是尝试在初始化 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 为空。

ERROR Error: formGroup expects a FormGroup instance. Please pass one in.

发生这种情况是因为您没有等待后端的响应来创建指向仍未定义的 formGroup 的 HTML 元素。您需要做的是同步创建一个空表单,然后在后端最终响应时使用 setValue 方法用值更新它。或者你可以添加一个布尔值让我们说命名为 loaded 到你的组件,当服务器响应时为真,然后在你的 html 表单上使用 *ngIf="loaded"

正如 itsundefined 所指出的那样,在呈现模板时未定义表单。

最简单的解决方案是使用

定义表单

<form *ngIf="settingsForm" [formGroup]="settingsForm" (ngSubmit)="onSubmit()" style="margin-top: 15px">

查看那里的 ngIf