zoukankan      html  css  js  c++  java
  • 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是为了父组件可以获取字组件,进行计数、调用字组件内部方法等等功能所提供的机制。。。。

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

  • 相关阅读:
    NFS服务安装
    Redhat 6.3 yum 本地源配置
    在redhat enterprise linux 6中部署samba
    React
    链表
    map, set
    二叉查找树
    数制间的相互转换
    二维数组
    拖拽
  • 原文地址:https://www.cnblogs.com/zheng-chuang/p/7418719.html
Copyright © 2011-2022 走看看