【问题标题】:Create unique variable name inside *ngFor在 *ngFor 中创建唯一的变量名
【发布时间】:2019-03-13 18:40:56
【问题描述】:

我正在尝试制作一个表格,当您单击按钮时,它需要在其正下方显示行。

我查看了this 的帖子,但找不到答案。

当我像下面这样使用它时,它可以工作,但问题是,它会显示所有其他隐藏的行,因为它们都共享相同的 collapse variable

这是工作示例,但不是 100% 正确:

<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(即index)附加到它来使collapse variable 独一无二,但随后出现以下错误:

解析器错误:在预期表达式的位置得到插值 ({{}})

这是我的尝试:

<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>

具体来说,在我的(click) 事件中,我怎样才能创建一个可以使用的唯一变量?

【问题讨论】:

    标签: javascript angular typescript


    【解决方案1】:
    (click)="{{collapse+i}}={{!collapse+i}}"
    

    应该是

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

    这允许您使用索引器来获取组件上的字段。它是否真的有效取决于您如何在组件上定义 collapse 字段。


    我个人更喜欢使用附加字段扩展 workQueues 数组中包含的类型。

    (click)="queue.collapsed = !queue.collapsed"
    
    ...
    
    <tr *ngIf="queue.collapsed">
    

    另一种选择是在*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

    【讨论】:

    • 让我快速尝试一下。不知道 Typescript/javascript 中的索引器,但我知道 C# 中的索引器
    • 这仍然会扩展所有隐藏的行,就像我发布的第一个代码块一样。
    • @monstertjie_za - 就像我说的,很难说它是否有效,因为我不知道组件中的代码。就我个人而言,我更喜欢答案中包含的选项 2 或 3。
    • 第三个选项产生:无法分配给引用或变量!认为最安全的是选项二。
    • @monstertjie_za - 请参阅stackblitz 了解选项 3 的工作演示。
    猜你喜欢
    • 1970-01-01
    • 2012-11-18
    • 1970-01-01
    • 2016-05-17
    • 1970-01-01
    • 1970-01-01
    • 2014-11-24
    • 1970-01-01
    • 2017-08-21
    相关资源
    最近更新 更多