使用Observables作为默认值的Angular 2 Formbuilder [英] Angular 2 Formbuilder with Observables as default values
本文介绍了使用Observables作为默认值的Angular 2 Formbuilder的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对Angular 2 Form(formbuilder)的默认值有疑问: 我的默认值是可观察值(我是从服务器上获取的),所以我不能像这样实现它们:
I have a problem with the default value of an Angular 2 Form (formbuilder): My default values are observables (which I'm retrieving from a server), so I can't implement them like this:
export class UserComponent implements OnInit{
userForm: ControlGroup;
userData: any; // Initialise the observable var
ngOnInit():any {
this.userData = this._dataService.getAllData() // My Observable
.subscribe(
data => {
this.userData = data;
}
);
this.userForm = this._formBuilder.group({
// below the default value
'username': [this.userData.username, Validators.compose([
this.usernameValid
])]
}
有人知道我需要改变什么?因为表单在输入字段中什么也不显示...
Someone an idea what I need to change? Because the form displays nothing inside the input fields...
推荐答案
我会尝试这样做,因为数据是异步加载的.因此,当响应存在/已收到时,您需要更新表单元素的值.
I would try this because the data are loaded asynchronously. So you need to update the value of form elements when the response is there / received.
ngOnInit():any {
this.userData = this._dataService.getAllData()
.subscribe(
data => {
this.userData = data;
this.userForm.controls.username.updateValue(
this.userData.username);
}
);
this.userForm = this._formBuilder.group({
'username': [this.userData.username, Validators.compose([
this.usernameValid
])];
}
这篇关于使用Observables作为默认值的Angular 2 Formbuilder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文