【问题标题】:angular2 toggle icons inside ngFor [duplicate]ngFor中的angular2切换图标[重复]
【发布时间】:2017-06-20 09:52:42
【问题描述】:

有人可以告诉我如何在执行 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>

【问题讨论】:

  • 你在为手风琴使用 jQuery 吗?
  • @RehbanKhatri 引导!!手风琴很好,它的工作!只有我需要知道如何切换 fa-plus 和 fa-minus。
  • 请出示您的手风琴代码,也许有一个可以使用的状态变量! :)
  • 应该可以“开”多天吗?
  • 我认为这是对您的特定问题的更好答案,摘要和详细信息元素是为此目的而构建的,而不是索引 - stackoverflow.com/a/42027647/7511922

标签: loops angular typescript ngfor angular-ng-if


【解决方案1】:

如果我理解正确,您可以在页面上只添加一个 &lt;i&gt; 而不是两个:

模板:

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

您可以将(click)="toggle[i] = !toggle[i] 放在*ngFor 模板内的任何html 元素上,这样它就会触发点击相关&lt;i&gt; 元素的切换。

【讨论】:

  • 我尝试了您的解决方案,但它会切换所有类别的图标。请查看随附的屏幕截图。谢谢
  • 是的,你说得对。我修改了代码,所以现在它应该只适用于使用索引的每个项目
【解决方案2】:

1) 您需要一个变量来存储当前选择的日期。

public SelectedDay:string = null;

2) 然后点击,设置选定的日期,

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

3) 使用*ngIfhidden 循环检查所选日期是否为同一天

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

这应该可行。

【讨论】:

    猜你喜欢
    • 2018-02-23
    • 2017-03-11
    • 2017-02-20
    • 1970-01-01
    • 2020-10-23
    • 2017-06-02
    • 2016-05-26
    • 2016-07-11
    相关资源
    最近更新 更多