具有Observables的Angular 2 Formbuilder作为默认值

时间:2016-05-04 15:20:46

标签: forms typescript angular observable formbuilder

我对Angular 2 Form(formbuilder)的默认值有问题: 我的默认值是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
        ])]
}

有人知道我需要改变什么吗?因为表单在输入字段中没有显示任何内容......

2 个答案:

答案 0 :(得分:7)

我会尝试这个,因为数据是异步加载的。因此,您需要在响应/接收时更新表单元素的值。

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

答案 1 :(得分:5)

你也应该能够这样做:

(?<Shape>rect|frect|fpie|spline|poly|line|fsec|fcir).+?(?!rect|frect|fpie|spline|poly|line|fsec|fcir)userdata\s\".*?attr=(?<AttributeType>\w+)\^(?<AttributePropertyString>.*?)\^(?=(?:END_FOXV))

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

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> 了,如果你有很多不同的字段需要从observables设置它们的默认值,它就会让事情变得容易一些。