首页 > 解决方案 > *ngIf on tr 未更新

问题描述

我有一个带有 ngIf 语句的 tr,该语句取决于函数结果 - 该函数由 click 事件(toggle(data.code))执行。查看我的代码:*TableData 是记录的集合

<tbody *ngFor="let data of TableData" (click)="toggle(data.code)">
   <tr *ngIf="isExpanded(data.code)">
     <td *ngfor="let column of columns">{{column.name}}</td>
   </tr>

这是组件中的功能:

codesArray: number[] = [];

isExpanded(code)
{
 return (code%10 == 0) || this.codesArray.includes(code); // The second part of the condition changes and should effect the tr
}


toggle(code)
{
    if (this.codesArray.includes(code))
    {
       this.codesArray.splice(this.codesArray.indexOf(code), 1);
    }
    else //This part should happen first and change the tr state 
    {
       this.codesArray.push(code); //This actually happens but the tr not appear  
    }
}

是否需要某种变化检测?

标签: angulardata-bindingbindingangular-ng-if

解决方案


不要在 body 上使用 ngFor。您将获得多个表格主体。尝试使用 ng-content。

<tbody>
  <ng-container *ngFor="let data of TableData">
   <tr (click)="toggle(data.code)">
      <ng-container *ngIf="isExpanded(data.code)">
        <td *ngfor="let column of columns">{{column.name}}</td>
     </ng-container>
   </tr>
  </ng-container>

推荐阅读