如何使用angular 4从父级获取子DOM元素引用

如何使用angular 4从父级获取子DOM元素引用,angular,angular-components,Angular,Angular Components,我需要使用angular 4从父组件获取子组件DOM引用,但我无法访问子组件DOM,请指导我如何实现 parent.component.html <child-component></child-component> <div> <table border="1"> <th>Name</th> <th>Age</th> <tbody #tab

我需要使用angular 4从父组件获取子组件DOM引用,但我无法访问子组件DOM,请指导我如何实现

parent.component.html

<child-component></child-component>
<div>
        <table border="1">
      <th>Name</th>
      <th>Age</th>
      <tbody #tableBody>
        <tr>
         <td>ABCD</td>
          <td>12</td>
        </tr>        
      </tbody>
        </table>
</div> 
<!-- You don't need to template reference variable on component -->   
<child-component></child-component> 
child.component.ts

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

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

<child-component></child-component>
<div>
        <table border="1">
      <th>Name</th>
      <th>Age</th>
      <tbody #tableBody>
        <tr>
         <td>ABCD</td>
          <td>12</td>
        </tr>        
      </tbody>
        </table>
</div> 
<!-- You don't need to template reference variable on component -->   
<child-component></child-component> 

名称
年龄
ABCD
12

需要引用父组件中的
表体。因此,将其添加到子组件
,并将其从主体t中删除

<child-component #tableBody></child-component>

要详细介绍Sachila Ranawaka,请回答:

首先,您需要

在父组件中,它应该是
ChildComponent
,而不是
ElementRef

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

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

除了Sachila和penleychan的好答案之外,您还可以通过组件的名称引用具有
@ViewChild
的组件:

parent.component.html

<child-component></child-component>
<div>
        <table border="1">
      <th>Name</th>
      <th>Age</th>
      <tbody #tableBody>
        <tr>
         <td>ABCD</td>
          <td>12</td>
        </tr>        
      </tbody>
        </table>
</div> 
<!-- You don't need to template reference variable on component -->   
<child-component></child-component> 

这将允许访问子组件,而不是作为子组件一部分的表体component@thilagabala这个答案不是错的,只是不完整。@12秒,如果我错了,请纠正我,如果我能完成上面的代码,我可以得到子组件方法和绑定值,而不是DOM。@thilagabala检查我的答案,认为它回答了你的问题。