简体   繁体   中英

populate FormBuilder from a service in Angular2

I have an Angular2 model that I'm populating via a service. I would like to use this model to then populate my form (built from FormBuilder ) so my users can edit the data.

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 .

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.setValue() does strict checks, while FormGroup.patchValue() does not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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