2016-03-11 50 views
0

我有以下形式:如何將表單輸入綁定到對象?

<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尚未在構造函數中定義。有任何想法嗎?

UPDATE

它的工作原理,當我在ngOnInit使用formBuilder - 但是,我不知道如果多數民衆贊成一個適當的方式做到這一點。

回答

1

只是移動

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

代碼後,你指定this.user(進入ngOnInit()

+0

是否建立雙向的數據格式和組件之間的綁定? – uksz

+0

當然,如果綁定值發生變化,則在每個事件之後進行角度檢查。 –

相關問題