首页 > 解决方案 > 在 Angular 中,我们如何在 ngFor 循环中定义的 ngIf 中使用局部变量?

问题描述

我是 Angular 新手,需要帮助来实现动态垂直选项卡:

我正在使用我在 ngIf 条件的 ngFor 循环中定义的变量 i 。我不知道如何在 ngIf 条件下使用变量 i 。我尝试了下面的代码,但它似乎不起作用。

 <div
          class="pb-5"
          *ngFor="let studentBatch of studentBatchList; let i = index"
        >
          <div
            id="{{ 'tab-content-' + (3 + i) }}"
            *ngIf="currTab == 'tab-content-(3+i)'"
          >
            {{ i + 3 }} <br />
            {{ studentBatch.batchId }}
          </div>
        </div>

TS代码:

showtabcontent(id) {
debugger;
id = 'tab-content-' + id;
// this.currTab = 'tab-content-0';
this.currTab = id;
alert(id);

}

标签: angular

解决方案


in*ngIf i+3被认为是一个字符串。在进行数学运算之前,您必须关闭单引号。

*ngIf="currTab == 'tab-content-' + (3 + i)"

完整示例:

<div class="pb-5" *ngFor="let studentBatch of studentBatchList; let i = index">
    <div id="{{ 'tab-content-' + (3 + i) }}" *ngIf="currTab == 'tab-content-' + (3 + i)">
        {{ i + 3 }} <br />
        {{ studentBatch.batchId }}
    </div>
</div>

推荐阅读