Angular 2 个以 Observables 作为默认值的 Formbuilder

Angular 2 Formbuilder with Observables as default values

我对 Angular 2 Form (formbuilder) 的默认值有疑问: 我的默认值是可观察值(我从服务器检索),所以我不能像这样实现它们:

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

您应该也可以这样做:

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

}

然后在您的模板中使用异步管道:

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

这样就不需要调用 updateValue() 如果你有很多不同的字段都需要从 observables 设置默认值,它会让事情更容易维护。