如何将表单输入绑定到对象?

时间:2016-03-11 13:47:22

标签: forms angular

我有以下表格:

<form role="form" [ngFormModel]="userEditForm"  (ngSubmit)="editUser(user)">
<div>
    <label for="username">Username</label>
    <input type="text" #username id="username" placeholder="Username" [ngFormControl]="userEditForm.controls['username']">
</div>
<div>
    <label for="firstName">First Name</label>
    <input type="text" #firstName id="firstName" placeholder="First Name" [ngFormControl]="userEditForm.controls['firstName']">
</div>
<div>
    <label for="lastName">Last Name</label>
    <input type="text" #lastName  id="lastName" placeholder="Last Name" [ngFormControl]="userEditForm.controls['lastName']">
</div>
<div>
    <label for="email">Email</label>
    <input type="text" #email  id="email" placeholder="Email" [ngFormControl]="userEditForm.controls['email']">
</div>
<button type="submit">Submit</button>

在我的组件中,我定义了:

        constructor(private _routeParams:RouteParams, private _formBuilder:FormBuilder, private _UserInject:UserInject){
    this.userEditForm = _formBuilder.group({
        'firstName': [this.user.firstName],
        'lastName': [this.user.lastName],
        'username': [this.user.username],
        'email': [this.user.email],
    })
}

ngOnInit(){
    let id = this._routeParams.get('userId');
    this.user = this._UserInject.getUser(id);
}

}

但是,这会产生错误,因为尚未在构造函数中定义this.user。有什么想法吗?

更新

当我在ngOnInit中使用formBuilder时它会起作用 - 但是,我不确定这是否是一种正确的方法。

1 个答案:

答案 0 :(得分:1)

移动

this.userEditForm = _formBuilder.group({
    'firstName': [this.user.firstName],
    'lastName': [this.user.lastName],
    'username': [this.user.username],
    'email': [this.user.email],
})

在您指定this.user(进入ngOnInit()

的代码之后