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()
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.
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.
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.
You can get a handle to the DOM element via ElementRef by injecting it into your component's constructor: constructor(private myElement: ElementRef) { ... }
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With