Angular 4无法读取属性' push'未定义的

时间:2017-12-09 08:21:42

标签: javascript angular typescript

export interface IComments{
    comments: string;
}

export interface IReport {
   reportdesc: string;
   comnts: [IComments]
}

export interface IRecord{
   rdesc: string;
   reportcomments: [IReport]
}

In template I get a single value of IRecord using comment  
<div>
<input [(ngModel)]="record.rdesc" name="rdesc">
<table>
<thead *ngFor="let d of record.reportcomments">
   <tr>
     <td>{{d.reportdesc}}</td>
  </tr>
  <tr *ngFor="let a of d.comnts">
    <td>{{a.comments}}</td>
   </tr>  
</thead>
</table>

在组件中我试图像这样推送一个空行

record=IRecord[]=[];

addRow(){
   this.record.reportcomments.push({
    rdes:'',
    comnts: {
         comments: ''
});

当我从模板调用addRow()来推送空行时出现错误

Error: TypeError: cannot read property 'push' if undefined.

请让我知道如何修复我的方法,以便我可以添加空行。 我已经检查了以前类似的问题而没有任何运气。 谢谢

2 个答案:

答案 0 :(得分:0)

record=IRecord[]=[];
record.reportcomments = [];

addRow(){
   this.record.reportcomments.push({
    rdes:'',
    comnts: {
         comments: ''}
});

将reportcomments定义为空数组不会导致错误reportcommentsundefined

record.reportcomments = [];

还有一件事是缺少关闭括号的评论,我相信你忘记在复制粘贴代码时添加,请检查此行comments: ''}

答案 1 :(得分:0)

正确初始化变量,如下所示:

let reports: [IReport] = [{}];
let record:IRecord = {rdesc: "My Report", reportcomments:reports};

模型应该定义所有可以为空的字段?如下:

export interface IComments{
comments: string;
}

export interface IReport {
reportdesc?: string;
comnts?: [IComments]
}

export interface IRecord{
rdesc?: string;
reportcomments?: [IReport]
}