简体   繁体   中英

Angular 2/4 pushing in array inside an object

I have been trying to push some comments in an array inside an object(Object is not an array but there is array in it) I spent quite a time cant get it to work. What I have is

export class test{
     recordname: string;
     comments: [{
         comment: string
      }]
}

Each time some one types a comment I want to add it to the comment array something like this

  addcomment: test;
addRow(){
    this.addcomment.comment.push({
        comment : 'first comment'})

I tried to add it using different ways cant seem to make it work. The message i get push is undefined. I cant use addcomment:test[]=[]; since this is form where vlaues are input and saved. Please let me know how can I push comment values

You have a spelling mistake on addcomment.comment (comments) Like this. 1. Define comments as an array. 2. Then just use the push function and pass in an object.

  export class test{
         recordname: string;
         comments: any[];
    }

this.addcomment.comments.push({
    comment : 'first comment'})

This example creates a new RecordItem which we can subsequently push items into, initialising an empty recordName and comment array.

export class Comment {
  comment: string
}

export class RecordItem {
  recordName: string;
  comments: Comment[]

  constructor(recordName: string, comments: Comment[]) {
    this.recordName = recordName;
    this.comments = comments;
  }
}

const recordItem = new RecordItem('', []);

recordItem.comments.push({ comment: 'Hey!!' });

Be sure to initialize always yours objects and array... you can do it in different ways so for example ...

export class test{
         recordname: string;
         comments: any[] = []; //set it as empty array ...intilized
    }

addcomment: test = new test(); //<-- INITIALIZE IT
addRow(){
    this.addcomment.comment.push({
        comment : 'first comment'});
}

Or if you don't like this approch ...

addcomment: test = new test(); //<-- INITIALIZE IT
    addRow(){

//check if nested array is undefined ..or other
 if(!this.addcomment.comment || this.addcomment.comment.length<=0)
     {
       this.addcomment.comment =[]; //<-- INITIALIZE AS EMPTY ARRAY
     }
        this.addcomment.comment.push({
            comment : 'first comment'});
    }

Hope it helps you!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM