Set reactive form after data loaded (async) - Angular 5

You can create a separate function to fill your form with data. You can call this function after getting data from an API.

Variant 1: setValue

Official angular documentation: setValue

With setValue, you assign every form control value at once by passing in a data object whose properties exactly match the form model behind the FormGroup.

Example:

updateValues(dataObject: any) {
  this.heroForm.setValue({
    name:    this.hero.name,
    address: this.hero.addresses[0] || new Address()
  });
}

Variant 2: patchValue

Official angular documentation: patchValue

With patchValue, you can assign values to specific controls in a FormGroup by supplying an object of key/value pairs for just the controls of interest.

Example:

updateValues(dataObject: any) {
  this.heroForm.patchValue({
    name: this.hero.name
  });
}

i've been confronted to this issue, i don't know if my solution is the best, but it work. The technique is to use a loaded: boolean that you initiate to false and once your data fully recived in your component you set it to true

here is an exemple :

.html:

<div *ngIf="loaded == false">
    <h2>loading ...</h2>
</div>
<div *ngIf="loaded == true">
   // your template goes here
</div>

and in your .ts:

loaded: boolean = false;

// your code ....

ngOnInit() {
  setTimeout(() => {
    this._dashboardService.routeChangeStarted();
  }, 0);
  this._activatedRoute.params.subscribe(params => {
    this.news["id"] = params["id"];
    this.getPartners().then(data => {
      this.getNews().then(data=>{
        this.setForm();

        // here is the important part!
        this.loaded = true
      })
    });
  });
}