You could just pass a static value (or a variable from *ngFor
or whatever)
<button (click)="toggle(1)" class="someclass">
<button (click)="toggle(2)" class="someclass">
When your HTMLElement
doesn't have an id
, name
or class
to call,
then use
<input type="text" (click)="selectedInput($event)">
selectedInput(event: MouseEvent) {
log(event.srcElement) // HTMInputLElement
}
do like this simply: (as said in comment here is with example with two methods)
import {Component} from 'angular2/core';
@Component({
selector: 'my-app',
template: `
<button (click)="checkEvent($event,'a')" id="abc" class="def">Display Toastr</button>
<button (click)="checkEvent($event,'b')" id="abc1" class="def1">Display Toastr1</button>
`
})
export class AppComponent {
checkEvent(event, id){
console.log(event, id, event.srcElement.attributes.id);
}
}
demo: http://plnkr.co/edit/5kJaj9D13srJxmod213r?p=preview
If you want to have access to the id
attribute of the button in angular 6 follow this code
`@Component({
selector: 'my-app',
template: `
<button (click)="clicked($event)" id="myId">Click Me</button>
`
})
export class AppComponent {
clicked(event) {
const target = event.target || event.srcElement || event.currentTarget;
const idAttr = target.attributes.id;
const value = idAttr.nodeValue;
}
}`
your id
in the value,
the value of value
is myId
.
There is no need to pass the entire event (unless you need other aspects of the event than you have stated). In fact, it is not recommended. You can pass the element reference with just a little modification.
import {Component} from 'angular2/core';
@Component({
selector: 'my-app',
template: `
<button #btn1 (click)="toggle(btn1)" class="someclass" id="btn1">Button 1</button>
<button #btn2 (click)="toggle(btn2)" class="someclass" id="btn2">Button 2</button>
`
})
export class AppComponent {
buttonValue: string;
toggle(button) {
this.buttonValue = button.id;
}
}
StackBlitz demo
Technically, you don't need to find the button that was clicked, because you have passed the actual element.
Angular guidance
For TypeScript users:
toggle(event: Event): void {
let elementId: string = (event.target as Element).id;
// do something with the id...
}