我试图通过在单击按钮时将对象的 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">×</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/