I have a form and a few functions that look like 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 now
}
In the above example, I can see setDefaultCountry setDefaultTimeZone getting called after buildForm. I can't understand why the new values are reflecting in the UI. All I see in the UI is the complete list of values. Its not showing the patch value. Do I need to trigger any events before or after setting default value ?
Also, when I print the form value after setting default ie, patchValue, I can see the updated value.
If it matters, I'm using an angular wrapper on select2 jquery plugin for country drop down
You need to import changeDetectionRef and call detectChanges().
import {ChangeDetectorRef} from '@angular/core';
Then inside your class,
constructor(private _cdr : ChangeDetectorRef){
}
later call _cdr.detectChanges()
after patchValue()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.