Reputation: 18699
I have the following form:
<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>
And in my component I have defined:
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);
}
}
However, this creates an error, because this.user is not yet defined in the constructor. Any ideas?
UPDATE
It works when I use formBuilder in the ngOnInit - however, I am not sure if thats a proper way to do it.
Upvotes: 0
Views: 625
Reputation: 657018
Just move
this.userEditForm = _formBuilder.group({
'firstName': [this.user.firstName],
'lastName': [this.user.lastName],
'username': [this.user.username],
'email': [this.user.email],
})
after the code where you assign this.user
(into ngOnInit()
)
Upvotes: 1