Home > Back-end >  When I change the value of a form variable (ngModel), another one changes too
When I change the value of a form variable (ngModel), another one changes too

Time:02-25

I want to implements a form in Angular that change the saved profile info in my app. So I have created an object called User.ts that contains all properties:

class User{
  name:string,
  surname:string,
  email:string
  .....
}

I have a component called profile, which allows me to see the saved user:

<div>
  <p>{{user.name}}</p>
  <p>{{user.surname}}</p>
  <p>{{user.email}}</p>
  ....
</div>

Besides this component contains the form in which the user info is been updated:

<div >
 <input type="text" [(ngModel)]="userForm.name">
 <input type="text" [(ngModel)]="userForm.surname">
 <input type="text" [(ngModel)]="userForm.email">
 .....
</div>

You can see that in the profile.ts I have defined two variables called user:User and userForm:User, the first ones for view the current info and the second for save the form inputs. When I get the user from the api and I save It in user, then I initialize the userForm like: this.userForm = this.user so the form at the beginning has the same value.

The problem is that when I try to change the inputs in form, the user object change too and replicates the value of userForm. I don't know why have this behavior, because ngModel directive points to userForm not to user.

CodePudding user response:

I have resolved the problem, when I did:

this.userForm  =  this.user

The two variables have the same instance of the User object, in other words are the same variable. I fixed the problem adding a method inside User class, that returns me the wanted data:

getUserPersonalData(){
   var personal_data = {
        name:this.personal_data.name,
        surname:this.personal_data.surname,
        email:this.personal_data.email
    }

CodePudding user response:

You can simple do

this.userForm  =  { ...this.user }

If you know that the user object has primitive types only.

Spread operator

  • Related