Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - detect the name of focused DOM element

I have a bunch of elements on the page and I need to detect the name of the selected element.

Example:

<select (click)="functionDetectName()" name="test1">
<select (click)="functionDetectName()" name="test2">
<select (click)="functionDetectName()" name="test3">

functionDetectName() {
console.log("What to put here to detect the name of the select element?");
}

So, when I click on the test1 select box, console log should output: test1, when on test2, it should output test2.

like image 795
jjj Avatar asked Jan 01 '26 00:01

jjj


2 Answers

You can pass $event to your functionDetectName() function and then get attribute name from passed data, for example:

<select (click)="functionDetectName($event)" name="test1">
<select (click)="functionDetectName($event)" name="test2">
<select (click)="functionDetectName($event)" name="test3">

functionDetectName(event: MouseEvent) {
    console.log(event.srcElement.name);
}
like image 191
Stefan Svrkota Avatar answered Jan 04 '26 02:01

Stefan Svrkota


You can just pass the name like

<select (click)="functionDetectName('test1')" name="test1">

or if you really want the attribute you can do

<select #self (click)="functionDetectName(self.getAttribute('name'))" name="test1">
like image 35
Günter Zöchbauer Avatar answered Jan 04 '26 04:01

Günter Zöchbauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!