Angular2: Form Build + asynchronous data loading

You can separate your username and email in Control object, than append it to form. You will have more control with that ( you can update it later ).

form: ControlGroup;
email: Control = new Control("");
name: Control = new Control("");
constructor(public fb: FormBuilder) {
 this.form = fb.group({
        email: this.email,
        name: this.name
    });

    setTimeout(() => {
        this.email.updateValue("invalid email");
        this.name.updateValue("Name");
    }, 3000);
}

Plunker example


I see several solutions to this:

  • Leverage an *ngIf to display the form only when the data are there
  • Leverage the @CanActivate decorator (if you use routing) to display the component where the form is, only when data are there
  • Use a temporary empty object to bind with the form. When the data are there, you can fill (or override) this object with the data received.

Here is a plunkr: https://plnkr.co/edit/metUkOB7Sqfyr9DtCLR0?p=preview.

Hope it helps you, Thierry