在Angular中如何使用ngFor循环定义的局部变量作为ngIf判断条件
问题修复方案
根因说明
你的*ngIf判断中,'tab-content-(3+i)'属于硬编码的固定字符串,Angular模板不会解析字符串内部的3+i表达式,导致实际判断时永远是currTab和固定值"tab-content-(3+i)"做对比,和你预期的动态拼接逻辑不符。
修复后的代码
HTML模板
<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即可,无需拼接前缀 this.currTab = id; alert(id); }
- 对应HTML修改:
<div class="pb-5" *ngFor="let studentBatch of studentBatchList; let i = index" > <div id="{{ 'tab-content-' + (3 + i) }}" *ngIf="currTab == 3 + i" > {{ i + 3 }} <br /> {{ studentBatch.batchId }} </div> </div>
内容的提问来源于stack exchange,提问作者Ahmad
相关产品推荐
相关产品推荐

