user5405873
user5405873

Reputation:

how to pre-populate form with ngModel binding

I have created a Modal page where i want to show pre-populated data to user whenever user edits data it must bind to my local collectDataInModalPage_afterEdit.

demo Here: https://stackblitz.com/edit/ionic-jse3zv?file=pages%2Fhome%2Fhome.ts

problem: [(ngModel)]="collectDataInModalPage_afterEdit" <= this ngModel is leaving form blank because it is set to blank in the begining here it is

    collectDataInModalPage_afterEdit = {
       "first_name":"",
       "last_name":"",
      "mobile_number":""
  };   

i took out [(ngModel)] for mobile_number field which is populated, see demo

Question : i want to pre-populate the form with this data => userDataBeforeEdit and want to collect data to this =>collectDataInModalPage_afterEdit

demo here:https://stackblitz.com/edit/ionic-jse3zv?file=pages%2Fhome%2Fhome.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  userDataBeforeEdit = {
    "first_name":"John",
  "last_name":"Doe",
  "mobile_number":"98869934445",
};

collectDataInModalPage_afterEdit = {    "first_name":"","last_name":"","mobile_number":""};      

  constructor(public navCtrl: NavController) {

  }

}

HTML

<ion-item>
    <ion-label floating>Name</ion-label>         
    <ion-input type="text" value="{{userDataBeforeEdit.first_name}}" [(ngModel)]="collectDataInModalPage_afterEdit.first_name"></ion-input>                
 </ion-item> 


 <ion-item>
    <ion-label floating>Last Name</ion-label>   
    <ion-input type="text" value="userDetails" [(ngModel)]="collectDataInModalPage_afterEdit.last_name"></ion-input>                
  </ion-item> 


   <ion-item>
    <ion-label floating>Phone Number</ion-label>   
    <ion-input type="text" value="{{userDataBeforeEdit.mobile_number}}"></ion-input>                         
  </ion-item> 

Please Help me thanks in Adavance!!!!

Upvotes: 1

Views: 2604

Answers (1)

AVJT82
AVJT82

Reputation: 73357

What I would do in this case is to just use Object.assign and skip the value altogether, so:

collectDataInModalPage_afterEdit = {};     

ngOnInit() {
  this.collectDataInModalPage_afterEdit = Object.assign({},this.userDataBeforeEdit)
}

Then you can just use this.collectDataInModalPage_afterEdit in your template with [(ngModel)]

DEMO: https://ionic-ovntia.stackblitz.io

I don't see how it would be possible to use value and ngModel in this case like you are trying to.

Other option would be, if this is a form (seems like it could be) is to build the form (with value) as such, that upon submit you can assign the form object directly to your variable collectDataInModalPage_afterEdit

Upvotes: 1

Related Questions