有人可以告诉我如何在进行ngFor时切换图标吗?
问题陈述: 我使用* ngFor循环遍历数组并显示类别名称。点击一天,我需要打开一个手风琴并显示类别详细信息(我可以这样做)。 一旦手风琴打开,我需要用fa-minus替换fa-plus图标,反之亦然,我只需要点击一天即可。
我如何有效地实现这一目标?
this.categoryList = [
{type: 'space', name: 'Space'},
{type: 'energy', name: 'Energy'},
{type: 'comfort', name: 'Comfort'},
{type: 'maintenance', name: 'Maintenance'},
{type: 'reporting', name: 'Reporting'}
];
HTML
<div class="{{category.type}}" *ngFor="let category of categoryList">
<div data-toggle="collapse" [attr.href]="'#'+'category-'+category.type">
<div class="title {{category.name}}">{{category.name}}</div>
<div>
<i class="fa fa-plus"></i> //needs to toggle between plus and minus
<i class="fa fa-minus"></i> //needs to toggle between plus and minus
</div>
</div>
<div class="collapse" id="category-{{category.type}}">
//details
</div>
</div>
答案 0 :(得分:12)
如果我理解你,你可以在页面上只有一个<i>
而不是两个:
<强>模板:强>
<div *ngFor="let day of daysInAWeek; let i = index">
<div>{{day}}</div>
<div>
<i class="fa" [ngClass]="toggle[i] ? 'fa-plus': 'fa-minus'" aria-hidden="true"></i>
</div>
<div class="details">Today is {{day}}</div>
<button (click)="toggle[i] = !toggle[i]">Toggle</button>
</div>
<强> TS:强>
daysInAWeek: string[] = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'];
toggle = {};
因此,您只需将该元素上的切换类切换为fa-plus
或fa-minus
您可以将(click)="toggle[i] = !toggle[i]
放在*ngFor
temlpate中的任何html元素上,这样它就会触发点按相关<i>
元素的切换。
答案 1 :(得分:0)
1)您需要一个存储当前选择日期的变量。
public SelectedDay:string = null;
2)然后点击,设置选定日期,
<div (click)="SelectedDay=day">{{day}}</div>
3)使用*ngIf
或hidden
<i class="fa fa-plus" *ngIf="SelectedDay!=day" aria-hidden="true"></i>
<i class="fa fa-minus" *ngIf="SelectedDay==day" aria-hidden="true"></i>
您的最终HTML应如下所示 -
<div *ngFor="let day of daysInAWeek">
<div (click)="SelectedDay=day">{{day}}</div>
<div>
<i class="fa fa-plus" *ngIf="SelectedDay!=day" aria-hidden="true"></i>
<i class="fa fa-minus" *ngIf="SelectedDay==day" aria-hidden="true"></i>
</div>
<div class="details">Today is {{day}}</div>
</div>
这应该有用。