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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…