Angular 2 Formbuilder with Observables as default values

Taremeh picture Taremeh · May 4, 2016 · Viewed 9.6k times · Source

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...

Answer

Thierry Templier picture Thierry Templier · May 4, 2016

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