efxzsh efxzsh - 4 months ago 11
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
ref
return an instance of
MyElement
.

How I can get
<my-element>
as a dom element ? Am I forced to keep am
ElementRef
in my class and do
ref.el.classList.add(...)
?

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

@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;

   ngAfterViewInit(){
     console.log(this.ref.nativeElement);
   }
}

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