【问题标题】:ngFor how to bind each element separatelyngFor 如何分别绑定每个元素
【发布时间】:2018-02-01 22:01:10
【问题描述】:

我正在尝试在 Angular 4 中构建一个仪表板。在那个仪表板中,我使用 *ngFor 来迭代一个 json(通过服务来)并在卡片中显示了一系列报告。在每张卡片的标题上都有一些图标,单击它们后将执行一些操作.. 例如刷新、下载、工具提示内的弹出信息、pin-unpin 等。

为此,我想到了使用变量来绑定这些元素,例如 (click)="function()",以及 [@animationTag]="variable" ,如下:

...
<div class="card" *ngFor="let r of reportCards; let x of index">
    <div class="card-header">
        {{r.reportName}}
        <div class="close" aria-label="Close">
            <i class="fa fa-thumb-tack" aria-hidden="true" [@pinUnpin]="isPinned" (click)="unpinCard($event)"></i>
        </div>
    </div>
    <div *ngIf="!ifMinimized" class="card-body">
       {{r.reportMainDesc}}
    </div>
    <div *ngIf="!ifMinimized" class="card-footer">
       {{r.reportFooterDesc}}
    </div>
</div>
...

对应的动画代码:

animations: [
trigger('pinUnpin', [
  state('pin', style({
      transform: 'rotate(0deg)',
  })),
  state('unpin', style({
      transform: 'rotate(90deg)',
  })),
  transition('pin => unpin', animate('300ms ease-in-out')),
  transition('unpin => pin', animate('300ms ease-in-out'))
]),
]

组件内部对应的函数:

unpinCard(pEvent) {
    this.ifMinimized = this.ifMinimized === true ? false : true;
    this.isPinned = this.isPinned === "pin" ? "unpin" : "pin";
}

问题:

所有功能都工作正常,但问题是每当我单击特定卡片上的一个(pin)图标时。如果对所有卡片执行这些操作,则意味着所有卡片都被最小化,并且(pin)所有卡片的图标都在同时动画化。

我可以猜到,这是由于变量 ifMinimizedifPinned 与通过 ngFor 生成的所有卡片绑定的。

请帮助我了解如何绑定单个元素,以便如果我单击一个元素的图标,则仅对该项目执行操作,而不是对 ngFor 生成的所有元素执行操作。

提前致谢。

【问题讨论】:

    标签: angular ngfor angular-ng-if


    【解决方案1】:

    只需将 reportCard (r) 传递给您的 unpinCard 函数并在该卡上设置 ifMinimized 和 isPinned:r['ifMinimized'] = !r['ifMinimized']

    或者去掉这个函数,简单的在html中输入:

    (click)="r.ifMinimized = !r.ifMinimized"
    *ngIf="!r.ifMinimized"
    

    【讨论】:

    • 非常感谢您的回复。它现在工作。感谢您的帮助。
    • 我面临的一个问题.. 如果我采用基于功能的方法,那么第一次单击图标动画不起作用,但第二次开始起作用。我已经在控制台中打印了 r[ifMinimized],第一次它是未定义的,但从第二次(点击)它显示为 false 或 true 等等。你能解释一下为什么会这样吗?
    • 给变量isPinned一个初始值(unpin或pin)
    • 抱歉延迟回复..我已经在构造函数中初始化了变量,但它仍然在发生...... this.ifMinimized = false; this.isPinned = "别针"; -- console.log 第一次显示 undefined
    • 您正在设置 ifMinimized 和 isPinned GLOBAL 变量。我们只是将这些变量放在每个 reportCards 对象中。也许这就是你问题的根源。您必须访问对象内部的变量,而不是全局变量。
    猜你喜欢
    • 2018-05-29
    • 2021-12-17
    • 1970-01-01
    • 2021-10-29
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多