Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get text from ElementRef?

Feels like this should be a pretty basic question...

I'm using a plugin that returns a DOM node / element that is NOT visible / rendered. I'm able to convert it easily to an ElementRef, with the nativeElement correctly populated.

How do I get the text of the element?

I know with AngularJS, I would do angular.elem(node).text()

like image 212
MattEnth Avatar asked Apr 19 '18 22:04

MattEnth


People also ask

How do I get ElementRef?

Getting ElementRef in Component ClassCreate 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 do you use ElementRef in angular 10?

We first import ElementRef from the @angular/core package, next we inject it via the directive's constructor. Next, in the ngOnInit method of the directive we use the nativeElement interface of ElementRef to access the native style property of the DOM element to which the directive is applied.

What is nativeElement?

native element, any of a number of chemical elements that may occur in nature uncombined with other elements. The elements that occur as atmospheric gases are excluded. structures of some 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

To get the text content of the element, use the textContent or the innerText property:

elementRef.nativeElement.textContent
elementRef.nativeElement.innerText

An example is shown in this stackblitz.


Here are some of the differences between them, as given in the MDN documentation:

  • While textContent gets the content of all elements, including <script> and <style> elements, innerText does not.
  • innerText is aware of style and will not return the text of hidden elements, whereas textContent will.
  • As innerText is aware of CSS styling, it will trigger a reflow, whereas textContent will not.
  • Unlike textContent, altering innerText in Internet Explorer (up to version 11 inclusive) not only removes child nodes from the element, but also permanently destroys all descendant text nodes (so it is impossible to insert the nodes again into any other element or into the same element anymore).
like image 121
ConnorsFan Avatar answered Sep 20 '22 08:09

ConnorsFan