ebakunin ebakunin - 2 months ago 23
AngularJS Question

Angular 2, RC6 - Referencing an HTML element without @ViewChild

Using Angular 2, RC6, I need to need to create a function that references the element in the template from which it fires. For example, if I have a

<div>
and click on it, the attached function would tell me about the
<div>
.

Here is a "broken" example (pseudo-code):

@Component({
selector: 'example',
template: `
<div id="example" (click)="myExampleFunction(this, $event)">
Some text
</div>
`
})
export class ExampleComponent {
public myExampleFunction(el: Element, ev: Event): void {
console.info('Element', el);
console.info('Event', ev);
}
}


This example will not work because the
this
parameter returns the entire
ExampleComponent
instead of just the
<div>
. The
$event
parameter works as expected, though.

Angular has introduced the concept of
@ViewChild
, which may work here. However, I would really prefer to keep the process simple and not have extraneous code. All I need is the referenced element. How can I do this?

Answer

You can either use

<div id="example" #example (click)="myExampleFunction(example, $event)">

or

<div id="example" (click)="myExampleFunction($event)">
export class ExampleComponent {
    public myExampleFunction(ev: Event): void {
        console.info('Element', ev.target);
        console.info('Event', ev);
    }
}
Comments