首页 > 解决方案 > 无法读取角度 4 中未定义的属性“0”

问题描述

我收到 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>

标签: angular

解决方案


*ngFor向上移动到 anng-container然后将 an*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>

文档

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


推荐阅读