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.


updateValues(dataObject: any) {
    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.


updateValues(dataObject: any) {

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 :


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

and in your .ts:

loaded: boolean = false;

// your code ....

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

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