Angular 2 中的 ViewChild 和 ViewChildren


https://segmentfault.com/a/1190000008695459

ViewChild

ViewChild 是属性装饰器,用来从模板视图中获取匹配的元素。视图查询在 ngAfterViewInit 钩子函数调用前完成,因此在 ngAfterViewInit 钩子函数中,才能正确获取查询的元素。

@ViewChild 使用模板变量名

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

@Component({
  selector: 'my-app',
  template: `
    

Welcome to Angular World</h1>

Hello {{ name }}

`, }) export class AppComponent { name: string = 'Semlinker'; @ViewChild('greet') greetDiv: ElementRef; ngAfterViewInit() { console.dir(this.greetDiv); } }

@ViewChild 使用模板变量名及设置查询条件

import { Component, TemplateRef, ViewChild, ViewContainerRef, AfterViewInit } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
    

Welcome to Angular World</h1>