Home > Mobile >  when i push a new user info in array it changes all previous infos
when i push a new user info in array it changes all previous infos

Time:11-02

''' ///user.model.ts

export interface User{
    id:number,
    firstname:string,
    lastname:string,
    personalnumber:string
}

/// app.component.ts

users: User[] = [];
user: User = {
    id: 0,
    firstname: "",
    lastname: "",
    personalnumber: ""
}



 addPerson(firstName: HTMLInputElement, lastName: HTMLInputElement, persNumber: HTMLInputElement) {
    this.user.firstname = firstName.value;
    this.user.lastname = lastName.value;
    this.user.personalnumber = persNumber.value;`enter code here`
    this.user.id  = 1;
    this.users.push(this.user)
    firstName.value = '';
    lastName.value = '';
    persNumber.value = '';
    console.log(this.users)
  }

'''

CodePudding user response:

array and object are reference types, since you are changing the user object and push it again it will change all elements in your array with the same value. Try

addPerson(firstName: HTMLInputElement, lastName: HTMLInputElement, persNumber: HTMLInputElement) {
 this.users.push({firstname: firstName.value, lastname: lastName.value, personalnumber: persNumber.value, id: this.user.id   })
 firstName.value = '';
 lastName.value = '';
 persNumber.value = '';
 console.log(this.users)
}

may be you don't even need that user object, you can create a var id that you increment each time

let id: number = 0;

addPerson(firstName: HTMLInputElement, lastName: HTMLInputElement, persNumber: HTMLInputElement) {
 this.users.push({firstname: firstName.value, lastname: lastName.value, personalnumber: persNumber.value, id: this.id   })
 firstName.value = '';
 lastName.value = '';
 persNumber.value = '';
 console.log(this.users)
}

CodePudding user response:

why not use spread operator to create a new object? futhermore, if you're using [(ngModel)] you needn't so "bizarra" function. Just

addPerson(user:User){
  user.id   
  this.users.push({...user}) //<--push a copy of the object
  this.user.firstName="";
  this.user.lastName="";
  ...
}

<input [(ngModel)]="user.firstName">
<input [(ngModel)]="user.lastName">
...
<button (click)="addPerson(user)">Add</button>
  • Related