1
votes

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

  1. Is there no way to bind the formbuilder fields with the response that I get from the api or the way I did it is the right way to do it?
  2. Inside the view instead of [(ngModel)]="firstName" shouldn't [(firstName)] work?

Will appreciate any help on this.

1
You seem to be mixing reactive and template forms; read through angular.io/docs/ts/latest/guide/reactive-forms.html which includes information on how to alter the current values in the form. Remove the [(ngModel)] binding entirely. - jonrsharpe
@jonrsharpe thanks for the tip, I am checking it out - Shairyar
Thanks @jonrsharpe that helped alot and i was able to implement the solution perfectly fine without using ngModel - Shairyar

1 Answers

2
votes

Use patchValue (or setValue) when you have received the response. In model-driven form do not use two-way-binding with ngModel. You can achieve what you want by setting the values to the form controls. Here let's set the values after you have received the values:

getProfileData() {
    this.service.profileData().then(data => {
        this.patchValues(data);  // call function to set the values  
    });
}

patchValues(data) {
  this.profile.patchValue({
     firstName: data.first_name,
     lastName: data.last_name
  })
}

Hope this helps! :)