Angular 2/4 can't read object in initForm()

前端 未结 2 1627
深忆病人
深忆病人 2020-12-22 03:17

I\'m creating an edit form in angular and I\'m confused about the lifecycle of the object that is returned from my backend server. When I make a call to my service in

相关标签:
2条回答
  • 2020-12-22 03:59

    First issue is that the call is asynchronous, so initForm is called before data has been retrieved. More info here: How do I return the response from an Observable/http/async call in angular2? So you need to call the method inside the callback.

    Tested the code, and so it seems, that when you add the initForm inside the callback it still doesn't work, even though setting the form with *ngIf="data". Still the form gets rendered before the form has been completely built, which throws error.

    So I see two possibilities here. Set a boolean value, e.g showForm and do not render the form unless showForm is true. You set the flag showForm as true, after data has been retrieved and after the form has been built.

    Other option would be to use setValue (or patchValue) where you enter the data to the fields after retrieving the data. Here's an example for you:

    build the form in your OnInit with empty values:

    this.payeeEditForm = new FormGroup({
      'company': new FormControl()
      'first_name': new FormControl()
      'last_name': new FormControl()
      'notes': new FormControl()
    })
    

    And when retrieved data call patchForm in the callback:

    this.subscription = this.payeeService.getPayee(this.id)
       .subscribe(data => {
          this.data = data;
          this.patchForm(); // set the values to the form
       });
    

    and your patchForm-method:

    patchForm() {
      this.payeeEditForm.setValue({
        company: this.data.company,
        first_name: this.data.first_name,
        last_name: this.data.last_name,
        notes: this.data.notes
      });
    }
    

    This seems to work fine! :) And setting the boolean flag worked too, if you prefer that!

    Here's a

    Demo

    0 讨论(0)
  • 2020-12-22 04:16

    The callback that you give to the subscribe method is executed later than the initForm method. Because the http call takes X amount of time.

    What you could do is to bind all of the properties to the ([ngModel]) in the inputs.

    0 讨论(0)
提交回复
热议问题