我有一个html按钮,有一个id,我想发送按钮的id,但不是在字段上写id,我想发送它作为this.id
,但我不能执行这个。
<button (click)="changeEnergy(this.id)" id="flash" [ngClass]="!theme?'btnEnergy1':'btnEnergy2'">
<i id="flashIcon" class="fa-solid fa-bolt iconFlash"></i>
</button>
我尝试手动编写id,它工作了,但我想发送它像this.id
,因为元素的id改变,它不是相同的id,所以我需要发送this.id
,但我不能。
你可以用angular的方式,使用一个模板变量来引用这个按钮。
<button (click)="changeEnergy(flash.id)" id="flash"
[ngClass]="!theme?'btnEnergy1':'btnEnergy2'" #flash>
<i id="flashIcon" class="fa-solid fa-bolt iconFlash"></i>
</button>
这里,注意#flash
引用了button元素,我们可以在纯js中使用它而不是它
首先欢迎堆栈溢出!
关于你的问题,你试图传递给changeEnergy
的id
是你的类的id
方法的值。为了访问元素的id,你必须写
<button (click)="changeEnergy($event)" id="flash" [ngClass]="!theme?'btnEnergy1':'btnEnergy2'">
<i id="flashIcon" class="fa-solid fa-bolt iconFlash"></i>
</button>
检索模板中的id
:
public changeEnergy(clickEvent: MouseEvent) {
const id = (event.target as HTMElement).id;
}
通过这种方式,你正在检索哪个元素被点击,你正在访问id