Home > database >  function(this.id) not working on click of angular
function(this.id) not working on click of angular

Time:11-18

I have a html button that has an id, and I want to send the id of the button, but not as writing the id on the field, I want to send it as this.id but I cannot perform this.

<button (click)="changeEnergy(this.id)" id="flash" [ngClass]="!theme?'btnEnergy1':'btnEnergy2'">
        <i id="flashIcon" ></i>
</button>

I tried by writing the id manually and it worked, but I want to send it like that as this.id because the id of the element changes, it is not the same id, so I need to send the this.id but I am not able to.

CodePudding user response:

You can do it in the angular way by using a template variable referring to this button.

<button (click)="changeEnergy(flash.id)" id="flash" 
    [ngClass]="!theme?'btnEnergy1':'btnEnergy2'" #flash>
            <i id="flashIcon" ></i>
</button>

Here, Note the #flash which references the button element which we can use instead of this in pure js

CodePudding user response:

welcome to stack overflow first of all!
Regarding your question, the id you are trying to pass to changeEnergy is the value of id method of yuour class. In order to access to the id of your element you have to write

<button (click)="changeEnergy($event)" id="flash" [ngClass]="!theme?'btnEnergy1':'btnEnergy2'">
        <i id="flashIcon" ></i>
</button>

And for retrieving the id in your template:

  public changeEnergy(clickEvent: MouseEvent) {
    const id = (event.target as HTMElement).id;
  }

In this way your are retrieving which element is click and you are accessing to the id

  • Related