I have a view for Edit Profile and I am fetching the data from remote server and then I want to populate the form with the data that is returned from the server. This is what I have tried and its working fine but I do not know if this is the correct way of doing it.
So inside the ngOnInit() I am creating the formBuilder the form in reality is alot bigger than this so for the sake of keeping the question simple i have only added two fields
ngOnInit() {
this.profile = this.formBuilder.group({
firstName: ['', [Validators.required]],
lastName: ['Last Name'],
});
//Get profile data
this.getProfileData();
}
getProfileData() is the method that then calls the service to get the profile data
getProfileData() {
this.service.profileData().then(data => {
this.firstName = data.first_name;
this.lastName = data.last_name;
});
}
And inside the view i have
<form [formGroup]="profile" (ngSubmit)="profileEditForm()">
<ion-item no-padding>
<ion-label stacked>First Name</ion-label>
<ion-input type="text" [(ngModel)]="firstName" formControlName="firstName"></ion-input>
</ion-item>
<ion-item no-padding>
<ion-label stacked>Last Name</ion-label>
<ion-input type="text" [(ngModel)]="lastName" formControlName="lastName"></ion-input>
</ion-item>
<button ion-button type="submit" [disabled]="!profile.valid" full>Submit</button>
</form>
My question is
- Is there no way to bind the
formbuilderfields with the response that I get from the api or the way I did it is the right way to do it? - Inside the view instead of
[(ngModel)]="firstName"shouldn't[(firstName)]work?
Will appreciate any help on this.
[(ngModel)]binding entirely. - jonrsharpe