【问题标题】:*ngIf on tr not updated*ngIf on tr 未更新
【发布时间】:2020-05-06 05:39:02
【问题描述】:

我有一个带有 ngIf 语句的 tr,它取决于函数结果 - 该函数由单击事件 (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  
    }
}

是否需要某种变更检测?

【问题讨论】:

  • 我的错误 - 插入到代码数组中的值不是我想要显示的值 - 代码似乎没问题。

标签: angular data-binding binding angular-ng-if


【解决方案1】:

您可以使用ChangeDetectorRef 功能ChangeDetectorRef.detectChanges() 手动触发更改检测

【讨论】:

    【解决方案2】:

    不要在 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>
    

    【讨论】:

    • ng-container 而不是 ng-content 但否则不要复制表格正文。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-31
    • 1970-01-01
    • 2017-01-01
    • 2017-06-14
    • 1970-01-01
    相关资源
    最近更新 更多