也许只是一种“时尚”但不管怎样。
我有以下几点是有效的:
// Template
<div *ngFor="let media of period.media">
.
.
.
<button #btn (click)="onDeleteClick(btn)" [attr.media-id]="media.ID">
{{'DELETE' | translate}}
</button>
</div>
//component.ts
this.period.media = [
{id: 123}, {id: 456}, ...
];
.
.
.
onDeleteClick(elem) {
console.log(elem._elementRef.nativeElement.getAttribute('media-id'));
}
它可以工作(the console shows 123, 456,...
),但使用_elemntRef访问nativeElelement听起来像个黑客(下划线表示私有属性,就像_privateVar一样,不是吗)。
那么,访问媒体或者更好的“nativeElement -id”属性会有什么更好的方式呢?
非常感谢你的任何提示。
编辑
这个问题的答案在user184994和JB Nizet的评论中。因为它们都正确地解决了问题,所以我不能设置"accepted“标志,因为它只能被分配一次。
因此,我正在编辑我的问题,以确认这一点。
发布于 2018-05-28 14:03:51
答案已经给出了,但我想再补充一点并回答它。你使用的是button,对于大多数浏览器来说,默认的按钮类型是submit。和如果你试图删除它,会得到提交的,如果你不想要它,你可以把它的类型改为type = "button"
。
<div *ngFor="let media of period.media">
<button type = "button" #btn
(click)="onDeleteClick(media)"
[attr.media-id]="media.ID">{{'DELETE' | translate}}</button>
</div>
另外,如果你想要,你可以只传递id,如果你需要或者想要的话,只要使用onDeleteClick(media.id)
就可以了,这在性能方面更好。如果不需要模板变量,可以将其删除。
//component.ts
this.period.media = [
{id: 123}, {id: 456}, ...
];
.
.
.
onDeleteClick(media) {
console.log(media.id);
}
如果只传递id,则需要更改语法,如下所示
onDeleteClick(id) {
console.log(id);
}
https://stackoverflow.com/questions/50555201
复制相似问题