我对Angular 2 Form(formbuilder)的默认值有问题:
我的默认值是observables(我正在从服务器检索),所以我不能像这样实现它们:
我的默认值是observables(我正在从服务器检索),所以我不能像这样实现它们:
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 ])] }
我会尝试这个,因为数据是异步加载的.因此,您需要在响应/接收时更新表单元素的值.
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 ])]; }