您好我正在尝试使用soem验证创建一个表单,当我创建一个选择框并尝试在ajax调用后将其设置为值时,我似乎遇到了一些问题。
这是构建表单的代码:
>=
}
export class StoreRegistrationComponent implements OnInit {
public countries: Array<StoreViewModel.CountryViewModel>;
public hasFormBeenSubmitted: boolean;
public storeRegistrationForm: ControlGroup;
public ngOnInit() {
this.storeDataService.getCountries().subscribe(countries => {
this.countries = countries
this.storeRegistrationForm.value.userCountryId = this.countries[0].id;
this.storeRegistrationForm.value.storeCountryId = this.countries[0].id;
});
this.buildStoreRegistrationForm();
}
private buildStoreRegistrationForm() {
this.storeRegistrationForm = this.formBuilder.group({
userCountryId: new Control('', Validators.compose([])),
storeCountryId: new Control('', Validators.compose([])),
});
}
现在我想要实现的是来自服务器的请求到达时,计数器根据数组中的第一个元素设置选择框的默认值。
我做错了什么?
答案 0 :(得分:2)
您可以将this.buildStoreRegistrationForm();
的呼叫转移到subscribe()
回调中,以延迟创建,直到countries
值到达:
public ngOnInit() {
this.storeDataService.getCountries().subscribe(countries => {
this.countries = countries
this.storeRegistrationForm.value.userCountryId = this.countries[0].id;
this.storeRegistrationForm.value.storeCountryId = this.countries[0].id;
this.buildStoreRegistrationForm();
});
}
或者您可以使用
更新值public ngOnInit() {
this.storeDataService.getCountries().subscribe(countries => {
this.countries = countries;
this.storeRegistrationForm.controls['userCountryId'].updateValue( this.countries[0].id);
this.storeRegistrationForm.controls['storeCountryId'].updateValue( this.countries[0].id);
});
}