请不要将其标记为重复 - 我已经尝试过以下链接:1)Hide/show individual items inside ngFor 2)Angular 2 - expand collapse table row 3)Hide/show individual items inside ngFor in angular 2
问题:
我在点击上一行中的链接时试图隐藏/显示表格行,如下所示: component.html
<div class="table-responsive" *ngFor="let total of totals; let i=index">
<table class="table">
<ng-container *ngIf="total">
<h4 class="productName">Product: {{total.projectGroup}}</h4>
<tr>
<th>Total LOC</th>
<th>Total Test Coverage</th>
<th>Total Coverage on New Code</th>
<th>Total Technical Debt</th>
<th>Total Issues</th>
</tr>
<tr>
<td>{{total.totalLOC}}</td>
<td>{{total.totalCoverage}}</td>
<td>{{total.totalNewCoverage}}</td>
<td>{{total.totalTechDebtDays}}</td>
<td><span *ngIf="total.totalCriticalIssues >= 0">Critical: </span>{{total.totalCriticalIssues}}
<span *ngIf="total.totalNonCriticalIssues >= 0">Non-critical: </span>{{total.totalNonCriticalIssues}}</td>
</tr>
<tr>
<td><a id="{{i}}" class ="a_link" (click)="toggle[total.projectGroup]=!toggle[total.projectGroup]; expand(total.projectGroup)"> Expand/Collapse</a></td>
</tr>
<tr [hidden]="!toggle[total.projectGroup]">
<div class="table-responsive">
<table class="table">
<tr class="table-header">
<th>Project Key</th>
<th>Quality Gate</th>
<th>LOC</th>
<th>Test Coverage</th>
<th>Coverage on New Code</th>
<th>Technical Debt</th>
<th>Issues</th>
</tr>
<tr *ngFor="let pjt of indProjects" class="table-condensed">
<td>{{pjt.projectKey}}</td>
<td>{{pjt.qualityGate}}</td>
<td>{{pjt.loc}}</td>
<td>{{pjt.coverage}}</td>
<td>{{pjt.newCoverage}}</td>
<td>{{pjt.techDebtDays}}</td>
<td><span *ngIf="pjt.criticalIssues >= 0">Critical: </span>{{pjt.criticalIssues}}
<span *ngIf="pjt.nonCriticalIssues >= 0">Non-critical: </span>{{pjt.nonCriticalIssues}}</td>
</tr>
</table>
</div>
</tr>
</ng-container>
</table>
它的工作如果我点击相同的"Expand/Collapse"链接2次 - 首先它显示然后它隐藏 . 但是如果我点击链接一次(显示)然后点击另一个链接,两个扩展都将在内部表中显示相同的数据(这是最后一次扩展的数据) . 我需要的是第一次扩展应显示与该链接相关的数据,第二次扩展应显示与第二次扩展相关的数据 .
请,任何指针都会有所帮助 . 如果我不清楚描述问题,请告诉我 .
1 回答
您在这里面临的问题是,您要将切换关联到for循环内的元素,而不实际创建不同的引用 . 这意味着所有生成的表行都将指向相同的引用,因此当您单击一个链接时,它将影响多个 .
由于您已经在
ngFor
循环上获得了index
,因此您应该将该索引与切换引用相关联 . 结果会变成这样的这样,动作的引用将保留在表的每一行上 .
但是为了简化你的目标,你可以做到
然后在你隐藏检查切换的地方,我也会替换
同
我相信你只需要模板标志 . 除非你需要一些更复杂的行为,否则我认为你根本不需要组件功能
我还注意到你有第二个没有索引的
ngFor
循环 . 这将导致问题,因为当您设置indProjects
属性时,它将具有所有行的相同值 . 因此,您需要将索引传递给expand(total.projectGroup, i)
函数,并在执行循环时在模板中将需要读取这样,您肯定每行都有唯一的列表