ngFor 总是返回数组中第一个对象的 id

ngFor alway returning id of first object in array

我正在尝试获取对象的 ID,方法是在单击按钮时将其分配给组件中声明的变量。但是,它似乎每次都只获取第一个对象ID。

这是 StackBlitz 的 link,它复制了我遇到的问题:

https://stackblitz.com/edit/angular-vcbzxf

如有任何帮助,我们将不胜感激。

更新 1: 您实际上可以使用 bootstrap 模态实现您想要的效果,只需进行如下所示的一些更改。

comment.component.html:

<div *ngFor="let comment of post.comments; let i = index">

  {{ comment.content }}
  <button data-toggle="modal" [attr.data-target]="'#confirmDeleteCommentModal' + comment.id">Get ID</button>

    <div class="fade modal" [attr.id]="'confirmDeleteCommentModal' + comment.id" tabindex="-1" role="dialog" aria-labelledby="confirmDeleteCommentModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="confirmDeleteCommentModalLabel">Delete Comment</h5>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" (click)="checkId(comment.id)">Delete</button>
                </div>
            </div>
        </div>
    </div>

</div>

通知 [attr.data-target]="'#confirmDeleteCommentModal' + comment.id" 添加到 Get ID 按钮和 [attr.id]="'confirmDeleteCommentModal' + comment.id" 添加到 bootstrap 模式。此外,模态现在包含在 *ngFor div element.

以前,Get ID 按钮的 data-target 总是设置为 confirmDeleteCommentModal,从技术上讲,我们只有一个 bootstrap 模式,id 设置为 confirmDeleteCommentModal,我认为这就是导致问题的原因,我们总是加载相同的(并且是第一个)bootstrap 模态。

已更新 stackblitz:https://stackblitz.com/edit/angular-3tmtwa


原回答(没有解决问题):

如果您要按照您最近的评论(如此处实施 - https://stackblitz.com/edit/angular-vcbzxf)进行操作,我想指出您可以按如下方式编写 comment.component.html

comment.component.html

<div *ngFor="let comment of post.comments">
    <div>
        {{showDelete ? 'Are you sure you want to delete?' : comment.content + ' id = ' + comment.id}}
        <button *ngIf="showDelete" (click)="showDelete = false">Cancel</button>
        <button (click)="(showDelete == false && showDelete = true) || checkId(comment.id)">Delete</button>
    </div>
</div>

Stackblitz 对其进行快速测试:https://stackblitz.com/edit/angular-q27xn7

虽然这可能不是您所做工作的重大改进,但我想我会指出实现类似结果的其他方法。