angular2 toggle icons inside ngFor [duplicate]

2019-01-26 16:41发布

This question already has an answer here:

Can some one please let me know how to toggle icons while doing ngFor?

Problem Statement: I'm using *ngFor to loop through an array and display category names. On click of day I need to open an accordian and show category details (I can do this). Once accordian opens I need to replace fa-plus icon with fa-minus and vice-versa and I need to do this only for clicked day.

How can I achieve this effectively?

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>

2条回答
戒情不戒烟
2楼-- · 2019-01-26 17:05

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.

查看更多
该账号已被封号
3楼-- · 2019-01-26 17:08

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.

查看更多
登录 后发表回答