【问题标题】:parent *ngfor has a child ngfor with a gallery - clicking the image affects all other child ngfor's - how to only affect the one being clicked父 *ngfor 有一个带有画廊的子 ngfor - 单击图像会影响所有其他子 ngfor - 如何只影响被单击的那个
【发布时间】:2020-01-08 14:00:05
【问题描述】:

我有一个 *ngFor 迭代 50 个成员。这些成员中的每一个都有一个图片库,当您单击图片时,可以循环浏览照片。一切正常,但样式意味着您可以看到前 3 张会员卡的顶部,因为每张卡的边距为 -10px、-20px、-30px

问题是,当您单击图库时,您可以看到前面的图库在遍历照片,这也是不可取的,我只想在当前顶级活动成员图库上进行迭代。我已经尝试过像 event.stopPropagation() 这样的方法来阻止事件冒泡,但它没有任何效果

    <div class="item" #mainParent *ngFor="let c of cards | async; trackBy: trackByCards; last as islast; let i=index">  
        <div class="content">
            <div class="image">
                <div class="gallery">
                    <img 
                    *ngFor="let h of c.album;  let x=index"
                    [src]="h"
                    (click)="changePhoto(x, c.album.length)" />
                </div>              
            </div>
            <div class="titles">
                <h1>
                    {{ c.name }}
                </h1>
                <h3>
                    {{ c.city }}
                </h3>
            </div>
        </div>
    </div>

点击改变照片的功能是

/**
 * Clicking photo changes the photo to the next one in the array
 * when it reaches the end of the album it goes back to the first photo
 */
changePhoto(index: number, albumCount: number) {
    if (index < albumCount - 1) {
        ++index;
    } else {
        index = 0;
    }
    this.activeFoto = index;
}

【问题讨论】:

  • 是不是因为您当前显示的所有画廊都访问了您的全局变量“activeFoto”?
  • 是的,后来我也明白了,我想哭:D 在这一点上,我宁愿跳过重新发明轮子并找到一个图书馆
  • 编程的黄金法则之一是避免重新发明轮子;D
  • 如果我的回答是对的,请采纳

标签: angular angular8


【解决方案1】:

根据我的评论,有一个局部变量,即:

this.activeFoto

由于其在 HTML 中的本地范围和使用,它影响了其他画廊,而不仅仅是打算改变的画廊。

【讨论】:

  • 在投票之前建议您进行编辑/评论可能是首选,因为我离答案不远。该变量不是全局的,你在那里是正确的。这是一个局部变量。
  • 话虽如此,更容易将变量概念化为相对于其包含的类具有全局范围,而不是考虑变量的局部范围级别。
猜你喜欢
  • 2019-02-08
  • 1970-01-01
  • 2016-06-17
  • 1970-01-01
  • 2018-06-17
  • 2022-01-26
  • 1970-01-01
  • 1970-01-01
  • 2021-06-30
相关资源
最近更新 更多