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

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

  • 相关阅读:
    Hyper-v: Snapshot merge
    解决Visual Studio 2010 “无法导入以下密钥文件” 错误
    Wix使用整理(二)
    Wix使用整理(一)
    C# 打开指定目录并定位到文件
    常用dos命令
    使用IE9、FireFox与Chrome浏览WPF Browser Application(.XBAP)的方式
    .NET Versioning and Multi-Targeting
    WPF-命令
    在WPF中显示动态GIF
  • 原文地址:https://www.cnblogs.com/zheng-chuang/p/7418719.html
Copyright © 2020-2023  润新知