Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast md ElementRef to HtmlElement in angular 2+

I have

 <input mdInput #try  placeholder="Favorite food" value="Sushi">

and I get it in ts by

 @ViewChild('try') myText : ElementRef;

and now I need to get approach to HtmlElement Function ,how I can Cast it?

and I don't want by this way add id="try" to mdInput and get it by :

var cel= document.getElementById("try");
like image 692
tal Avatar asked Aug 13 '17 08:08

tal


People also ask

How do I use ElementRef?

To manipulate the DOM using the ElementRef , we need to get the reference to the DOM element in the component/directive. Create a template reference variable for the element in the component/directive. Use the template variable to inject the element into component class using the ViewChild or ViewChildren.

How can I set the value of a native element in angular?

You need to use renderer. setProperty() instead of renderer.

Why do we use ElementRef in angular?

Angular ElementRef is a wrapper around a native element inside of a View. It's simply a class that wraps native DOM elements in the browser and allows you to work with the DOM by providing the nativeElement object which exposes all the methods and properties of the native elements.

Can we access DOM element inside angular component constructor method?

You can get a handle to the DOM element via ElementRef by injecting it into your component's constructor: constructor(private myElement: ElementRef) { ... }


1 Answers

myText.nativeElement will contain a reference to the DOM element. Assert myText.nativeElement as HTMLElement:

let domElement = this.myText.nativeElement as HTMLElement;
like image 166
Saravana Avatar answered Sep 16 '22 18:09

Saravana