我在For循环中有多张卡片。在每张卡中,我想使用链接或按钮在卡中显示和隐藏内容。我没有唯一的ID来分配要切换的每个div。有办法吗?
以下代码仅在第一个卡中扩展或折叠内容,即使在任何卡中单击了“扩展”或“折叠”按钮。
<div *ngFor="let result of results">
<div class="clr-col-lg-12 clr-col-12">
<div class="card">
<div class="card-block">
<div *ngIf="result?.name">
<h3 class="card-title">{{result.name}}</h3>
</div>
<div class="expandCollapse">
<button (click)="toggle($event)">
{{buttonName}}
</button>
</div>
<div class="expandCollapseContent" *ngIf="showRuleContent">
<div *ngIf="result?.cTag">
<h5>C Tag</h5>{{result.cTag}}
</div>
</div>
</div>
</div>
</div>
</div>
组件
public showRuleContent:boolean = false;
public buttonName:any = 'Expand';
toggle($event) {
this.showRuleContent = !this.showRuleContent;
// CHANGE THE NAME OF THE BUTTON.
if(this.showRuleContent)
this.buttonName = "Collapse";
else
this.buttonName = "Expand";
}
答案 0 :(得分:2)
您可以使用一个数组来保存每个元素的可见状态,而不是单个变量。
模板
<div *ngFor="let result of results;let i = index">
<div class="clr-col-lg-12 clr-col-12">
<div class="card">
<div class="card-block">
<div *ngIf="result?.name">
<h3 class="card-title">{{result.name}}</h3>
</div>
<div class="expandCollapse">
<button (click)="toggle(i)">
{{hideRuleContent[i] ? 'Expand' : 'Collapse'}}
</button>
</div>
<div class="expandCollapseContent" *ngIf="!hideRuleContent[i]">
<div *ngIf="result?.cTag">
<h5>C Tag</h5>{{result.cTag}}
</div>
</div>
</div>
</div>
</div>
</div>
组件
public hideRuleContent:boolean[] = [];
public buttonName:any = 'Expand';
toggle(index) {
// toggle based on index
this.hideRuleContent[index] = !this.hideRuleContent[index];
}
答案 1 :(得分:1)
这是在列表中隐藏/显示项目的巧妙方法。您可以使用模板元素属性而不是将某些内容存储在数组中。
注意它如何利用 Angular's template variables (#ListItem)。
temp := x^2 + y^2;
2 2
temp := x + y
f := unapply(temp, [x,y]);
f := proc (x, y) options operator, arrow; y^2+x^2 end proc
f(1, 2);
5
g := subs(__dummy=temp,
(x,y)->__dummy);
g := proc (x, y) options operator, arrow; y^2+x^2 end proc
g(1, 2);
5
CSS 示例:
<ng-container *ngFor="let item of list">
<div #ContentElement></div>
<button (click)="toggle(ContentElement)">
</ng-container>
如果您想从 DOM 中删除元素而不是隐藏:
// Maybe there are other ways to do this part, here is an example.
// Idea here is to toggle a class.
close(e: HTMLElement) {
e.classList.toggle('hidden');
}