Angular ViewChild

viewchild

// 使用方法
git clone https://git.oschina.net/mumu-osc/learn-component.git
cd learn-component
git pull origin viewchild
npm install 
ng serve
<!-- test-view-child.component.html -->
<div class="panel panel-primary">
  <div class="panel-heading">父组件</div>
  <div class="panel-body">
    <child-one></child-one>
    <child-one></child-one>
    <child-one></child-one>
    <child-one></child-one>
  </div>
</div>
// test-view-child.component.ts
import { Component, OnInit, ViewChild, ViewChildren, QueryList } from '@angular/core';
import { ChildOneComponent } from './child-one/child-one.component';

@Component({
  selector: 'test-view-child',
  templateUrl: './test-view-child.component.html',
  styleUrls: ['./test-view-child.component.scss']
})
export class TestViewChildComponent implements OnInit {
  // @ViewChild(ChildOneComponent)
  // childOne:ChildOneComponent;
  @ViewChildren(ChildOneComponent)
  children:QueryList<ChildOneComponent>;

  constructor() { }

  ngOnInit() {
  }

  ngAfterViewInit():void{
    // console.log(this.childOne);
    this.children.forEach((item)=>{
      console.log(item);
      //动态监听子组件的事件
      item.helloEvent.subscribe((data)=>{
        console.log(data);
      });
    });
  }
}
// child-one.component.ts
import { Component, OnInit, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'child-one',
  templateUrl: './child-one.component.html',
  styleUrls: ['./child-one.component.scss']
})
export class ChildOneComponent implements OnInit {
  @Output()
  helloEvent:EventEmitter<string>=new EventEmitter<string>();

  constructor() { }

  ngOnInit() {
  }
  
  public sayHello():void{
    this.helloEvent.emit("hello...");
  }
}

什么是ViewChild

从上面的代码可以看出viewchild是为了父组件可以获取字组件,进行计数、调用字组件内部方法等等功能所提供的机制。。。。

具体用法:比如,可以在轮播图组件中,进行获取所插入图片的数量等,从而实现一个通用的轮播图组件

posted @ 2017-08-23 16:10  郑闯  阅读(1377)  评论(0编辑  收藏  举报