angular2 toggle icons inside ngFor [duplicate]

只谈情不闲聊 提交于 2019-11-29 11:02:01

If I understand you right you can have just one <i> on the page instead of having two:

template:

<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 = {};

So you can toggle just toggle classes on that element to be fa-plus or fa-minus

You can put (click)="toggle[i] = !toggle[i] on any html element inside your *ngFor temlpate so it will trigger the toggle on click for related <i> element.

1) You will need a variable that stores which day is currently selected.

public SelectedDay:string = null;

2) Then on click, set selected day,

<div (click)="SelectedDay=day">{{day}}</div>

3) Check if selected day is the same day in loop using *ngIf or 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>

Your final HTML should look like this -

<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>

This should work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!