简体   繁体   English

从Angular2中的服务填充FormBuilder

[英]populate FormBuilder from a service in Angular2

I have an Angular2 model that I'm populating via a service. 我有一个通过服务填充的Angular2模型。 I would like to use this model to then populate my form (built from FormBuilder ) so my users can edit the data. 我想使用此模型来填充我的表单(从FormBuilder构建),以便我的用户可以编辑数据。

Here is what I am currently doing, but I get errors for fields that exist in my model that are not being exposed in my form. 这是我当前正在执行的操作,但是对于模型中存在但未在表单中公开的字段,我会遇到错误。

  ...
  ngOnInit(): void {
    this.buildForm();
    this.get('1');
  }
  get(id: string) {
    this.myModelsService.get(id)
      .subscribe(
        d => {
          this.myModel = d;
          this.myForm.setValue(d);
        },
        error => console.log(error)
      );
  }

This works, however I get errors like Cannot find form control with name: incidentTimeStamp . 这行得通,但是出现诸如Cannot find form control with name: incidentTimeStamp类的错误。

Should I be first deleting attributes that I know do not have corresponding form controls? 我应该首先删除我知道没有相应表单控件的属性吗? Or is there a better way to do what I am trying to do? 还是有更好的方法来做我想做的事情?

Being able to populate fields for edit seems like a pretty basic building block, and this seems like it is way harder than it should be. 能够填充字段以进行编辑似乎是一个非常基本的构建块,并且这似乎比应做的要困难得多。

The solution is to use FormGroup.patchValue() 解决方案是使用FormGroup.patchValue()

FormGroup.setValue() does strict checks, while FormGroup.patchValue() does not. FormGroup.setValue()不严格把关,同时FormGroup.patchValue()没有。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM