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是爲了父組件能夠獲取字組件,進行計數、調用字組件內部方法等等功能所提供的機制。。。。css

具體用法:好比,能夠在輪播圖組件中,進行獲取所插入圖片的數量等,從而實現一個通用的輪播圖組件html

相關文章
相關標籤/搜索