【问题标题】:Cannot read property '0' of undefined in angular 4无法读取角度 4 中未定义的属性“0”
【发布时间】:2018-07-19 20:10:33
【问题描述】:

我收到 TypeError Cannot read property '0' of undefined 。下面是代码。 fsIncomeStatementTable 是 fsIncomeStatementTable 是一个数组数组。我注意到有一行未定义。我如何检查 为那一行?

如果我尝试我的解决方案说无法绑定 ngif,我会收到错误

代码

<tbody>
   <tr *ngFor="let row of fsIncomeStatementTable | slice:1" [ngClass]="{'net-cost': row[0] === incomeStatementStyles[0] || row[0] === incomeStatementStyles[1] || row[0] === incomeStatementStyles[2] || row[0] === incomeStatementStyles[3]}">
      <td>{{row[0]}}</td>
      <td *ngFor="let cell of row | slice:1">{{cell | shortNumberDivideByThousand: 0 | number:'.0-0'}}</td>
   </tr> 
</tbody>

解决方案

<tbody>
  <tr *ngFor="let row of fsIncomeStatementTable | slice:1" [ngClass]="{'net-cost': row[0] === incomeStatementStyles[0] || row[0] === incomeStatementStyles[1] || row[0] === incomeStatementStyles[2] || row[0] === incomeStatementStyles[3]}">
     <td>{{row[0]}}</td>
     <td *ngif="row !== undefined"> </td>
     <td *ngFor="let cell of row | slice:1">{{cell | shortNumberDivideByThousand: 0 | number:'.0-0'}}</td>
   </tr> 
</tbody>

【问题讨论】:

  • row 本身总是被定义的,因为您没有向集合添加“未定义”。您使用的指令看起来像是对“行”的子属性进行操作,并且子属性变为空。您需要检查正在使用的属性,然后在指令中处理它

标签: angular


【解决方案1】:

*ngFor 向上移动到ng-container,然后将*ngIf 放在tr 上。

<ng-container *ngFor="let row of fsIncomeStatementTable | slice:1">
  <tr *ngIf="row" [ngClass]="{'net-cost': row[0] === incomeStatementStyles[0] || row[0] === incomeStatementStyles[1] || row[0] === incomeStatementStyles[2] || row[0] === incomeStatementStyles[3]}">
    <td>{{row[0]}}</td>
    <td *ngif="row !== undefined"> </td>
    <td *ngFor="let cell of row | slice:1">{{cell | shortNumberDivideByThousand: 0 | number:'.0-0'}}</td>
  </tr>
</ng-container>

来自docs

Angular 是一个不会影响样式或布局的分组元素,因为 Angular 不会将其放入 DOM 中。

【讨论】:

  • 出现错误无法绑定到“ngif”,因为它不是“td”的已知属性。 ("> {{row[0]}} ]*ngif="row !== undefined">
  • 确保i 大写。例如*ngIf
【解决方案2】:

您尝试在此处访问您的行

 <td>{{row[0]}}</td>

即使它是未定义的。

您的代码应该如下所示:

 <td *ngif="row !== undefined">{{row[0]}}</td>
 <td *ngif="row === undefined"> </td>

【讨论】:

  • 出现错误无法绑定到“ngif”,因为它不是“td”的已知属性。 ("> {{row[0]}} ]*ngif="row !== undefined"> –
  • 导入角度 FormsModule.
  • 我已将导入添加到其组件中,但出现相同的错误
  • 你需要在你的 app.module 中导入它
猜你喜欢
  • 1970-01-01
  • 2019-02-28
  • 1970-01-01
  • 1970-01-01
  • 2018-10-28
  • 2018-09-19
  • 2018-02-22
  • 1970-01-01
  • 2017-11-19
相关资源
最近更新 更多