Angular 2 Formbuilder with Observables as default values

萝らか妹 提交于 2019-12-07 01:29:24

问题


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


回答1:


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



回答2:


You should also be able to 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 pipe as so:

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

This way there is no need to call updateValue() and it makes things a bit easier to maintain if you have a lot of different fields which all needs their default values set from observables.



来源:https://stackoverflow.com/questions/37031910/angular-2-formbuilder-with-observables-as-default-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!