@viewChild
作用一:选择组件内节点
<!--视图  -->
<div #mydiv><input></div>
// 选择
@ViewChild(‘mydiv‘) mydiv: ElementRef
// 返回原生节点
let el = this.mydiv.nativeElement // 
// 使用原生方法
let ipt = el.querySelector(‘input‘)
作用二:选择子组件可调用自组件内的函数
子组件:
@Component({ selector: ‘user-profile‘ }) 
export class UserProfile { 
  constructor() {} 
  sendData() { //send data } 
}
当前组件
import { Component, ViewChild } from ‘@angular/core‘; 
import { UserProfile } from ‘../user-profile‘; 
@Component({ template: ‘<user-profile (click)="update()"></user-profile>‘, }) 
export class MasterPage { 
  // ViewChild takes a class type or a reference name string. 
  // Here we are using the type 
  @ViewChild(UserProfile) userProfile: UserProfile 
  constructor() { } ngAfterViewInit() { 
  // After the view is initialized,
   this.userProfile will be available this.update(); 
  } 
  update() { 
    this.userProfile.sendData(); 
  } 
}
@ViewChild 选择组件模板内的节点
@ContentChild 选择当前组件引用的子组件 @ContentChild(组件名)
@ViewChildren 和 @ContentChildren 则为对应的复数
import { Component, ContentChild, AfterContentInit } from ‘@angular/core‘;
import { ChildComponent } from ‘./child.component‘;
@Component({
    selector: ‘exe-parent‘,
    template: `
      <p>Parent Component</p>  
      <ng-content></ng-content>
    `
})
export class ParentComponent implements AfterContentInit {
    @ContentChild(ChildComponent)
    childCmp: ChildComponent;
    ngAfterContentInit() {
        console.dir(this.childCmp);
    }
}
import { Component } from ‘@angular/core‘;
@Component({
    selector: ‘exe-child‘,
    template: `
      <p>Child Component</p>  
    `
})
export class ChildComponent {
    name: string = ‘child-component‘;
}
import { Component } from ‘@angular/core‘;
@Component({
  selector: ‘my-app‘,
  template: `
    <h4>Welcome to Angular World</h4>
    <exe-parent>
      <exe-child></exe-child>
    </exe-parent>
  `,
})
export class AppComponent { }
// 添加类
this.renderer2.addClass(el, ‘active‘)
// 移除了类
this.renderer2.removeClass(el, ‘active‘)
// 设置样式
this.renderer2.setStyle(el, ‘height‘, ‘10px‘)
// 移除样式
this.renderer2.removeStyle(el, ‘height‘)
// 设置属性
this.renderer2.setAttribute(el, ‘data-id‘, ‘id‘)
// 移除属性
this.renderer2.removeAttribute(el, ‘data-id‘)
// 设置值
this.renderer2.setValue(ipt, ‘some str‘)
// 监听事件
this.renderer2.listen(el, ‘click‘, (e)=>{console.log(e)}) //el|‘window‘|‘document‘|‘body‘
// 其他类似
createElement 创建元素
createComment 动态创建组件
createText 创建文本节点
destroyNode 销毁节点
appendChild 插入子节点
insertBefore (parent: any, newChild: any, refChild: any): void
removeChild(parent: any, oldChild: any): void 移除子元素
selectRootElement(selectorOrNode: string|any): any
parentNode(node: any): any
nextSibling(node: any): any
 angular5 @viewChild ElementRef renderer2
原文:http://www.cnblogs.com/mttcug/p/8004359.html