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

时间:2017-12-15 05:03:48

标签: angular angular-components

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

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> 

3 个答案:

答案 0 :(得分:7)

扩展Sachila Ranawaka回答:

首先你需要<child-component #childComp></child-component>

在您的父组件中,而不是ElementRef,它应该是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);
  }
}

对于您的孩子组件:

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

答案 1 :(得分:2)

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

parent.component.html

<!-- You don't need to template reference variable on component -->   
<child-component></child-component> 

然后在parent.component.ts中

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);
  }
}

答案 2 :(得分:0)

需要引用父组件中的tableBody。然后将其添加到child-component并将其从tbody

中删除
<child-component #tableBody></child-component>