I know I can obtain the DOM element of a component with
constructor(el: ElementRef){}
But how do I access its children (e.g. by searching by class or id) and host?
el.nativeElement.children el.nativeElement.parent el.nativeElement.host
all don't work.
I've searched all over for an answer, with no luck. Thank you very much for any help.
EDIT Thanks to yurzui's comment I realised el.nativeElement.children
works after the component's view is initialised. However I still can't access the host element.
Also, as JB Nizet pointed out, it is inelegant do manipulate DOM elements in Angular2. The only thing about my DOM element I need in the component's class, though, is the element's width. If I knew how to bind this value to a class attribute, I would have solved the issue without accessing the DOM. I had previously tried something like
<div [width] = "style.width"></div>
(width
an attribute of the class of my component, whose view containse the above div) but I can't get it to work.
@ViewChild is a local component template querying mechanism, that cannot see the internals of its child components. By injecting references directly into our component class, we can easily write any coordination logic that involves multiple elements of the template.
The ViewChild or ViewChildren decorators are used to Query and get the reference of the DOM element in the Component. ViewChild returns the first matching element and ViewChildren returns all the matching elements as a QueryList of items. We can use these references to manipulate element properties in the component.
Try to use your code in ngAfterViewInit event.
And you need to use parentNode property instead parent
export class App { el: ElementRef; constructor(el: ElementRef){ this.el = el; }, ngAfterViewInit() { const hostElem = this.el.nativeElement; console.log(hostElem.children); console.log(hostElem.parentNode); } }
https://plnkr.co/edit/iTmsNaIoU9NNUEFRe4kG?p=preview
Since this.el.nativeElement.children returns Array of child nodes, you can simply do this.el.nativeElement.children[0].
import { Component, AfterViewInit, ElementRef } from '@angular/core'; export class MyComponent implements ngAfterViewInit { el: ElementRef; constructor(el: ElementRef){ this.el = el; } ngAfterViewInit() { console.log(this.el.nativeElement.children[0]); console.log(this.el.nativeElement.children[0].offsetHeight); } }
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