efxzsh efxzsh - 1 year ago 109
TypeScript Question

Get the reference of an element

Just to understand how things work.

Let say I have the fellowing code

<my-element #ref></my-element>
<button (click)="ref.classList.add("prettify")"></button>

It will throw an error, because
return an instance of

How I can get
as a dom element ? Am I forced to keep am
in my class and do

I tried with the form element too

<form #ref></form> // return a ref about the element
<form #ref="ngForm"></form> return a ref about NgForm

Answer Source

@ViewChild can be used to get an element reference as shown here.

<my-element #ref></my-element>

//<---<button (click)="ref.classList.add("prettify")"></button> I don't understand purpose of having this line. What does button do?

in Component,

import {ViewChild,ElementRef} from '@angular/core';

export class AppComponent{

   @ViewChild('ref') ref:ElementRef;


DEMO : https://plnkr.co/edit/uP7CYM?p=preview

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download