ebakunin ebakunin - 1 year ago 136
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

and click on it, the attached function would tell me about the

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

selector: 'example',
template: `
<div id="example" (click)="myExampleFunction(this, $event)">
Some text
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
parameter returns the entire
instead of just the
. The
parameter works as expected, though.

Angular has introduced the concept of
, 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 Source

You can either use

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


<div id="example" (click)="myExampleFunction($event)">
export class ExampleComponent {
    public myExampleFunction(ev: Event): void {
        console.info('Element', ev.target);
        console.info('Event', ev);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download