我有一個窗體和幾個如下所示的函數。Angular 2使用patchValue從REST API設置數據
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
}
在上面的例子中,我可以看到setDefaultCountry setDefaultTimeZone在buildForm之後被調用。我不明白爲什麼新的價值觀反映在用戶界面中。我在UI中看到的是完整的值列表。它沒有顯示補丁值。在設置默認值之前或之後,是否需要觸發任何事件?
此外,當我在設置默認值即打印補償值後打印表格值時,我可以看到更新後的值。
如果它的事項,我使用的是選擇2 jQuery插件的角度包裝器國家下拉
我試過補丁之後調用ChangeDetectorRef。這並不奏效。 – TechCrunch
NgZone也沒有運氣:( – TechCrunch