// 使用方法 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是为了父组件能够获取字组件,进行计数、调用字组件内部方法等等功能所提供的机制。。。。css
具体用法:好比,能够在轮播图组件中,进行获取所插入图片的数量等,从而实现一个通用的轮播图组件html