Angular2父子组件数据传递之@ViewChild获取子组件详解

@ViewChild的作用是声明对子组件元素的实例引用,意思是通过注入的方式将子组件注入到@ViewChild容器中,你可以想象成依赖注入的方式注入,只不过@ViewChild不能在构造器constructor中注入,因为@ViewChild会在ngAfterViewInit()回调函数之前执行。

@VIewChild提供了一个参数来选择将要引入的组件元素,可以是一个子组件实例引用, 也可以是一个字符串(两者的区别,后面会讲)

//子组件实例引用
@ViewChild(ChildrenComponent) child:ChildrenComponent; 

//字符串
@ViewChild("child") child2;

下面我们来介绍一下两种用法。

1、当传入的是一个子组件实例引用

   children.component.ts

import { Component} from "@angular/core";

@Component({
    selector:'app-children',
    templateUrl: './children.component.html',
    styleUrls: ['./children.component.less']
})
export class ChildrenComponent{
     fun1(){
      alert('子组件方法');
     }
}

parent.component.ts

import { Component} from "@angular/core";

@Component({
    selector:'app-parent',
    templateUrl: './parent.component.html',
    styleUrls: ['./parent.component.less']
})
export class ParentComponent{
        @ViewChild(ChildrenComponent) child:ChildrenComponent;
       
         onClick(){
               this.child.fun1();
            }
}

1、这里传入一个子组件实例引入,定义了一个变量child接收

2、定义了Onclick()方法,用于页面触发点击事件,模拟调用子组件中的方法

parent.component.html

  <div class="parent_div">
           <p>父组件</p>
           <div>
               <input type="button" value="调用子组件方法" (click)="onClick()">
           </div>
           <!-- 子组件指令 -->
           <app-children></app-children>
     </div>

父组件模版中input绑定了一个click点击事件,页面触发点击调用onClick()方法

2.当传入的是一个字符串

parent.component.ts

 import { Component} from "@angular/core";

@Component({
    selector:'app-parent',
    templateUrl: './parent.component.html',
    styleUrls: ['./parent.component.less']
})
export class ParentComponent{
        @ViewChild('myChild') child;
       
         onClick(){
               this.child.fun1();
            }
}

1、@ViewChild传入一个字符串myChild,变量child接收。其它不变

parent.component.html

    <div class="parent_div">
           <p>父组件</p>
           <div>
               <input type="button" value="调用子组件方法" (click)="onClick()">
           </div>
           <!-- 子组件指令 -->
           <app-children #myChild></app-children>
     </div>

两种效果是一样的。

sometimes the hardest part isn't letting go,but rather start over
原文地址:https://www.cnblogs.com/zhumeiming/p/10339113.html