在Angular2 FormGroup中设置值

时间:2016-08-24 19:31:34

标签: angular angular2-forms

我正在尝试在FormGroup中设置值。我的角度版本是rc-5。这是我的组成部分;

AADTBuilder

这是我的HTML;

import { Component, Input, OnInit } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { Router, ActivatedRoute } from '@angular/router';
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';

@Component({
     templateUrl: 'myHtmlPage.html',
     providers: [
          UserService
     ]
})

export class UserDetailComponent implements OnInit {
     user: User;
     userDetailForm: FormGroup;

     constructor(private userService: UserService, private route: ActivatedRoute, private formBuilder: FormBuilder) {
          this.userDetailForm = this.formBuilder.group({
               email: new FormControl('', [<any>Validators.required])
          });
     }

     getUser(id: number) {
         this.userService.getById(id)
             .subscribe((res) => { this.user = res.data; }, /*do stg*/, () => { this.userDetailForm.controls['email'].setValue(this.user.email); });
     }

     ngOnInit() {
         let id;
         this.route.params.subscribe(params => id = +params['id']);
         this.getUser(id);
     }

     //...
}

我的用户&#39;类;

<form [formGroup]="userDetailForm" (ngSubmit)="editUser(userDetailForm.value)">
<div class="card card-inverse col-md-6 offset-md-3" style="background-color: #333; border-color: #333;">
    <div class="card-block">
        <h4 class="card-title row">
            Details
        </h4>
        <div class="form-group row">
            <div>
                <label for="email" class="card-subtitle">Email</label>
                <div>
                    <input class="form-control" type="text" id="email" formControlName="email" />
                </div>
            </div>
        </div>
    </div>
</div>

此代码没有问题,它可以正常工作。但是如果我想在“用户”中添加一些属性呢?类?我应该每次都在这样的情况下设置值吗?onCompleted&#39;打回来?当我将代码从构造函数移动到&#39; onCompleted&#39;订阅回调,我得到以下错误:

export class User {
     email: string;
}

当我将代码从构造函数移动到&#39; ngOnInit&#39;方法,它不能获得form group expects a form group instance. please pass one in 的值,因为订阅工作异步。有人帮我吗?

1 个答案:

答案 0 :(得分:0)

我在rc5中工作,但我不再使用REACTIVE_FORM_DIRECTIVES指令了。在我的Shared.Module.ts中,我导入和导出ReactiveFormsModule。如果它解决了您的问题或需要更多帮助,请告诉我。

@NgModule({
    imports: [CommonModule, FormsModule, ReactiveFormsModule, ...],
    declarations: [...],
    exports: [CommonModule, FormsModule, ReactiveFormsModule, ...]
})