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

标签 angular5 bootstrap-modal variable-assignment ngfor

我试图通过在单击按钮时将对象的 ID 分配给组件中声明的变量来获取该对象的 ID。然而,它似乎每次都只获取第一个对象 ID。

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

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

任何帮助将不胜感激。

最佳答案

更新 1:您实际上可以使用引导模式实现您想要的效果,只需进行如下所示的少量更改。

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"已添加到获取ID按钮和[attr.id] ="'confirmDeleteCommentModal' + comment.id" 添加到引导模式。此外,模态现在包含在 *ngFor div 元素中。

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

更新了 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

虽然与您所做的相比,这可能不是一个很大的改进,但我想我只想指出实现类似结果的其他方法。

关于angular5 - ngFor 总是返回数组中第一个对象的 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50851488/

相关文章:

javascript - 控制 bootstrap 确认模式中的确认按钮

c++ - 复合赋值 E1 op= E2 不等同于 E1 = E1 op E2

bootstrap-4 - 角度 5 引导选择 : selectpicker is not a function

Django:如何使用模态作为更新对象的形式

angular - PrimennGTreeTable 图标不可见

javascript - Meteor 的 Iron Router 不关闭模态对话框

file - 使用 Erlang 将整个文本文件读入变量,进行文本替换并将修改后的文件写入新目录

C++ 按值传递和按引用传递函数内的赋值之间有区别吗?

angular - 使用 Angular 动态地向元素添加属性

angular - Angular 中的事件数组