Create unique variable name inside *ngFor

问题: I am trying to make a table that, when you click a button, it needs to display the row directly beneath it. I have had a look at this post, but I could not find an answer...

问题:

I am trying to make a table that, when you click a button, it needs to display the row directly beneath it.

I have had a look at this post, but I could not find an answer from it.

When I have it like below, it works, but the problem is, it displays all other hidden rows since they all share the same collapse variable.

This is the working example, but not 100% correct:

<table>
<thead>
  <th>Path out of this queue</th>
  <th *ngFor="let role of roles">{{role.RoleName}}</th>>
</thead>
<tbody>
  <ng-container *ngFor="let queue of workQueues; let i = index">
    <tr>
      <td><button (click)="collapse=!collapse">{{queue.WorkQueueName}}</button></td>
      <td *ngFor="let role of roles">
        <input type="checkbox" />
      </td>
    </tr>
    <tr *ngIf="collapse">
      Yay...
    </tr>
  </ng-container>
</tbody>

I thought I would be able to make the collapse variable unique, by appending the i, which is the index, to it, but then I get the following error:

Parser Error: Got interpolation ({{}}) where expression was expected

Here is my attempt:

<table>
<thead>
  <th>Path out of this queue</th>
  <th *ngFor="let role of roles">{{role.RoleName}}</th>>
</thead>
<tbody>
  <ng-container *ngFor="let queue of workQueues; let i = index">
    <tr>
      <td><button (click)="{{collapse+i}}={{!collapse+i}}">{{queue.WorkQueueName}}</button></td>
      <td *ngFor="let role of roles">
        <input type="checkbox" />
      </td>
    </tr>
    <tr *ngIf="{{collapse+i}}">
      Yay...
    </tr>
  </ng-container>
</tbody>

Specifically, in my (click) event, how can I make a unique variable that could be used?


回答1:

(click)="{{collapse+i}}={{!collapse+i}}"

should be

(click)="this[collapse+i] = !this[collapse+i]"

This allows you to use an indexer to obtain the field on the component. If it actually works depends on how you have collapse fields defined on your component.


Personally I would prefer extending the type contained in the workQueues array with an additional field.

(click)="queue.collapsed = !queue.collapsed"

...

<tr *ngIf="queue.collapsed">

An other alternative is to define a new field in the *ngFor.

<ng-container *ngFor="let queue of workQueues; let i = index; let isCollapsed = true">
<tr>
  <td><button (click)="isCollapsed = !isCollapsed">{{queue.WorkQueueName}}</button></td>
  <td *ngFor="let role of roles">
    <input type="checkbox" />
  </td>
</tr>
<tr *ngIf="!isCollapsed">
  Yay...
</tr>
</ng-container>

stackblitz

  • 发表于 2019-03-14 22:59
  • 阅读 ( 195 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除