I'm trying to send the id of a element from html to the function, this because it changes in the ts, so I have a click function but function(this.id) doesnt work here is my code
the html
<button id="btnNext" (click)="nextGeneral(this.id)">next</button>
the ts
nextGeneral(id:number){
alert(id)
}
CodePudding user response:
If I understand correctly, you want the id
attribute from the <button>
(i.e. btnNext
) to be passed into the nextGeneral()
function (although this function is currently expecting a number
not a string
, so correct me if I'm wrong).
This is how you could achieve that dynamically:
.html
<button id="btnNext" (click)="nextGeneral($event)">next</button>
.ts
nextGeneral(event: PointerEvent){
const id: string = (event.target as HTMLElement).id
alert(id)
}
CodePudding user response:
this
is not available inside a template. You might want to use 'btnNext' as the parameter instead, but its too vague from your description.
So replace the template's (click)=nextGeneral(this.id)
with (click)=nextGeneral('btnNext')
and it will work and also might fit your requirements. Does it fit?
CodePudding user response:
One of the cleanest way to achieve it is by using template reference in angular.
<button id="btnNext" #myButton (click)="nextGeneral(myButton)">next</button>
Inside your nextGeneral
nextGeneral(button: HTMLButtonElement) {
alert(button.getAttribute('id'));
}
Running Solution - https://stackblitz.com/edit/angular-ivy-ohxfa5?file=src/app/app.component.html,src/app/app.component.ts