Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find children and parents of a DOM element in Angular2

Tags:

angular

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.

like image 723
Emilio Ferrucci Avatar asked Apr 04 '16 15:04

Emilio Ferrucci


People also ask

What is@ ViewChild?

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

What is difference between ViewChild and ViewChildren?

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.


2 Answers

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

like image 155
yurzui Avatar answered Sep 29 '22 03:09

yurzui


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);   } } 
like image 23
Uliana Pavelko Avatar answered Sep 29 '22 04:09

Uliana Pavelko