Search code examples
angularangular-components

How to get the child DOM element reference from Parent using angular 4


I need to get the child component DOM reference from parent component using angular 4, but i can't access child component DOM, please guide me how to achieve this.

parent.component.html

<child-component></child-component>

parent.component.ts

import { Component, Input, ViewChild, ElementRef, AfterViewInit } from '@angular/core';

@Component({
  selector: 'parent-component',
  templateUrl: './parent.component.html'
})
export class ParentComponent implements AfterViewInit {
  @ViewChild('tableBody') tableBody: ElementRef;
  constructor(){
    console.log(this.tableBody);//undefined
  }
  ngAfterViewInit() {
       console.log(this.tableBody);//undefined
   }
}

child.component.ts

import { Component } from '@angular/core';
@Component({
  selector: 'child-component',
  templateUrl: './child.component.html'
})
export class ChildComponent { 
}

child.component.html

<div>
        <table border="1">
      <th>Name</th>
      <th>Age</th>
      <tbody #tableBody>
        <tr>
         <td>ABCD</td>
          <td>12</td>
        </tr>        
      </tbody>
        </table>
</div> 

Solution

  • To expand on Sachila Ranawaka answer:

    First you need <child-component #childComp></child-component>

    In your parent component, instead of ElementRef it should be ChildComponent:

    @Component({
      selector: 'parent-component',
      templateUrl: './parent.component.html'
    })
    export class ParentComponent implements AfterViewInit {
      @ViewChild('childComp') childComp: ChildComponent;
      constructor(){
      }
      ngAfterViewInit() {
        console.log(this.childComp.tableBody);
      }
    }
    

    For your child component:

    @Component({
      selector: 'child-component',
      templateUrl: './child.component.html'
    })
    export class ChildComponent { 
      @ViewChild('tableBody') tableBody: ElementRef;
    }