akila arasan
akila arasan

Reputation: 747

adding items to array during emit overrides the previous element in angular 4

I am working on a project , where i have a use case to add a new list item on click of add button and the added data must be rendered as a new list item.

add content component

import { Component,Output,EventEmitter} from '@angular/core';
@Component({
  selector: 'add-content',
  template:`<input type='text' [(ngModel)] = 'content'/>
            <button (click) = 'addNewContent(content)'>`
})
export class AddContentComponent {
  @Output() newContent: EventEmitter < any > = new EventEmitter();
  content: any;
  constructor() {
    this.content = {};
  }
  addNewContent(content) {
    if (content) {
      this.content.body = content;
      this.newContent.emit(this.content);
    }
  }
}

contentlistcomponent

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

@Component({
   selector:'content-list',
   template:`<ul>
              <li *ngFor="let content of contentList">{{content.body}}</li>
              <add-content (newContent)=getContent($event)></add-content>
              </ul>`
   
});
export class ContentListComponent {
contentList:Array<any>;
constructor(){
 this.contentList = [];
}
getContent(content){
if(content){
  this.contentList.push(content);
}
}

when first content is added the list renders the typed content correctly however when second content is added the previous content is also replaced by the new content and two list items with last item's content is displayed.As I am newbie , I couldn't figure out where I am going wrong.Could anyone help me with this issue?

EDIT I have created a plunker showing the issue,

https://plnkr.co/edit/Wgj4I9yAQjSxi1C91vnb?p=preview

Upvotes: 2

Views: 1322

Answers (1)

Jayakrishnan
Jayakrishnan

Reputation: 4294

The problem is that object reference is maintained for content variable in getContent function. You need to do following to push to contentList without maintaining reference of previous values.

getContent(content){
 if(content){
  var copy = Object.assign({}, content);
  this.contentList.push(copy);
  }
}

Hope it helps !!

Upvotes: 4

Related Questions