简体   繁体   English

角度2/4推入对象内部的数组

[英]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[]=[]; 我不能使用addcomment:test [] = []; since this is form where vlaues are input and saved. 因为这是输入和保存vlaues的表格。 Please let me know how can I push comment values 请让我知道如何推送评论值

You have a spelling mistake on addcomment.comment (comments) Like this. 像这样,您在addcomment.comment(注释)上有一个拼写错误。 1. Define comments as an array. 1.将注释定义为数组。 2. Then just use the push function and pass in an object. 2.然后,只需使用推功能并传递一个对象即可。

  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. 本示例创建一个新的RecordItem ,随后我们可以将其放入其中,初始化一个空的recordNamecomment数组。

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!! 希望对您有帮助!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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