Angular 2 Formbuilder with Observables as default values

I have a problem with the default value of an Angular 2 form (formbuilder): My default values ​​are observable (which I retrieve from the server), so I cannot implement them as follows:

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 ])] } 

Does anyone know what I need to change? Since the form does not display anything inside the input fields ...

+7
angular forms typescript observable formbuilder
source share
2 answers

I would try this because the data is loaded asynchronously. Therefore, you need to update the value of the form elements when the response is received / 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 ])]; } 
+5
source share

You should also do this:

 data: Observable<any>; ngOnInit():any { this.data = this._dataService.getAllData(); this.data .map((data) => { return this._formBuilder.group({ username: [ this.data.username, Validators.compose([this.usernameValid]) ] }) .subscribe((userForm) => { this.userForm = userForm }) } 

Then, in your template, use the async channel as follows:

 <form *ngIf="data | async" [formGroup]="userForm"> //...// </form> 

Thus, there is no need to call updateValue() , and this simplifies the work if you have many different fields for which all default values ​​are set from observables.

+3
source share

All Articles