代码之家  ›  专栏  ›  技术社区  ›  monstertjie_za

在*ngFor内创建唯一的变量名

  •  0
  • monstertjie_za  · 技术社区  · 7 年前

    我看了一眼 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 ,但随后我得到以下错误:

    分析器错误:获取了预期表达式所在的插值({}})

    以下是我的尝试:

    <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) 事件,如何生成可使用的唯一变量?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Igor    7 年前
    (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

    推荐文章