使用 *ngIf 按索引切换 class

using *ngIf to toggle class by index

我想通过使用 *ngIf 来切换显示上面有 *ngFor 的 class,这样我就可以用它的索引切换 div。这是我的代码的样子:

<div *ngFor="let scenario of scenarios; let j = index">
  <div (click)="toggle(j)" class="edit-btn">
    <p>Edit</p>
  </div>
  <div *ngIf="show" class="input-wrapper">
      <div class="spectrum-inputs" *ngFor="let s of scenario.time; let i = index;trackBy:trackByIndex;">
         <input ...>
      </div>
  </div>
</div>

.ts 文件:

public show:boolean = false;

  toggle(index) {
    this.show[index] = !this.show[index];
  }

我正在将索引 j 传递给 (click)="toggle(j)" 按钮。

您应该初始化一个长度为 scenarios.length 的数组来存储每个场景 div 的状态,例如 -

public show = new Array(scenarios.length).fill(false);

然后你可以这样做

toggle(index) {
  this.show[index] = !this.show[index];
}

并在 HTML 中与 *ngIf="show[j]" 一起使用,它读取特定场景 div 的状态,例如 -

<div *ngFor="let scenario of scenarios; let j = index">
  <div (click)="toggle(j)" class="edit-btn">
    <p>Edit</p>
  </div>
  <div *ngIf="show[j]" class="input-wrapper">
      <div class="spectrum-inputs" *ngFor="let s of scenario.time; let i = index;trackBy:trackByIndex;">
         <input ...>
      </div>
  </div>
</div>

现在您的 show 变量包含一个布尔值

所以我设法做到了:

<div *ngFor="let scenario of scenarios; let j = index">
  <div (click)="toggle(j)" class="edit-btn">
    <p>Edit</p>
  </div>
  <div *ngIf="show === j" class="input-wrapper">
      <div class="spectrum-inputs" *ngFor="let s of scenario.time; let i = index;trackBy:trackByIndex;">
         <input ...>
      </div>
  </div>
</div>
public show: number;

    toggle(index) {
    if (this.show == index) {
      this.show = -1;
    }
    else {
      this.show = index;
    }
  }