1

I am not familiar with Angular 2, 3, 4 & 5 and I am trying to get a better understanding of Angular 6.

Problem: I am pushing an user object to the users array then when I change the value of inputs, all the object inside the array is also changing.

component.ts

public data; //user input id,age,first_name,last_name
public users: User[] = [];

constructor() {
    this.data = {};
}

ngOnInit() {
}

btnClick = function () {
    //push the user input to array
    this.users.push(this.data);
};

Please check my sample code here: https://stackblitz.com/edit/angular-1ztg1k

2
  • 2
    How are you changing the user input? Can you please post the full code including the template? Commented Sep 9, 2018 at 17:15
  • @AmardeepBhowmick you can check my sample code here. Thank you for your help. stackblitz.com/edit/angular-1ztg1k Commented Sep 9, 2018 at 17:28

1 Answer 1

1

You are bound to the same data reference after pushing the data object in the array. After adding the item in the array, the text input is still referring to the earlier data reference through [(ngModel)]="data.first_name" which is in the array.

All you have to do is re-initialize the data instance to an empty object literal.

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  users = new Array();
  data = {}

  btnClick = function (){
    this.users.push(this.data);
    this.data = {};
  }
}

I forked your code and modified it: https://stackblitz.com/edit/angular-klrrjd

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much @Amardeep Bhowmick. You saved my day. :)
np :) @MarkRobinGaspar

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.