angular2 forms - Angular 2 set data from REST API using patchValue -


i have form , few functions below.

  ngoninit() {         this.buildform();         this.loaddata();         this.success = false;     }      loaddata(): void {         this.countryservice.getcountries().subscribe(list => {             this.countries = new select2mapper('countrycode', 'name').getdata(list);             this.setdefaultcountry();         });     }      setdefaultcountry(): void {         console.log('setting default country');         console.log(this.accountcreateform.get('company').value);         this.accountcreateform.get('company').patchvalue({             countrycode: "us"         });     }      buildform(): void {          this.accountcreateform = this.fb.group({             company: this.fb.group({                 companyname: ['', [wpvalidator.companyname]],                 countrycode: ['', [validators.required]]             }),             administrative: this.fb.group({                 firstname: ['', [wpvalidator.namemandatory]]             })         });          console.log('form built');          this.accountcreateform.valuechanges             .subscribe(data => this.onvaluechanged(data));          this.onvaluechanged(); // (re)set validation messages      } 

in above example, can see setdefaultcountry setdefaulttimezone getting called after buildform. can't understand why new values reflecting in ui. see in ui complete list of values. not showing patch value. need trigger events before or after setting default value ?

also, when print form value after setting default i.e., patchvalue, can see updated value.

if matters, i'm using angular wrapper on select2 jquery plugin country drop down

you need import changedetectionref , call detectchanges().

import {changedetectorref} '@angular/core'; 

then inside class,

constructor(private _cdr : changedetectorref){  } 

later call _cdr.detectchanges() after patchvalue()


Comments