I need to fill Reactive Form inputs with data I get from service
I am getting user data from the service and I need to fill the user data in form inputs
My code:
user: any;
constructor(public _UsersService: UsersService) {
_UsersService.getUser(this.qr_url).subscribe(data => {
this.user = data;
});
}
editUserForm: FormGroup = new FormGroup({
'name': new FormControl(this.user.name, [Validators.required, Validators.minLength(3), Validators.maxLength(100)]),
});
This code gives me error Property 'user' is used before its initialization.
note: I tried to console.log() the user and it has data not empty
CodePudding user response:
There are multiple ways.
A) you can define your form within the subscribe:
user: any;
editUserForm: FormGroup;
constructor(public _UsersService: UsersService) {
_UsersService.getUser(this.qr_url).subscribe(data => {
this.user = data;
this.editUserForm = new FormGroup({
name: new FormControl(this.user.name, [
Validators.required,
Validators.minLength(3),
Validators.maxLength(100),
]),
});
});
}
B) You can define the form as empty and then use patchForm to update the values from the subscription. https://ultimatecourses.com/blog/angular-2-form-controls-patch-value-set-value#patchvalue