首页 文章

Angular 2从其父组件调用子组件中的函数

提问于
浏览
20

我想知道最好的方法,如果有不同的方法 . 我正在尝试从其父组件中调用子组件中的函数 . 所以,如果我有:

<parent>
    <child></child>
</parent>

...和 child 具有名为 show()hide() 的函数,如何调用 parent 中的任何一个?

2 回答

  • 51

    在您的模板内:

    <parent (click)="yourChild.hide()">
        <child #yourChild></child>
    </parent>
    

    在组件内部(option1):

    import { ..., ViewChild, ... } from '@angular/core';
    
    // ...
    
    export class ParentComponent {
       @ViewChild('yourChild') child;
    
       ngAfterViewInit() {
          console.log('only after THIS EVENT "child" is usable!!');
          this.child.hide();
       }
    }
    

    在您的组件内部(option2):

    import { ..., ViewChild, ... } from '@angular/core';
    import { ..., ChildComponent, ... } from '....';
    
    // ...
    
    export class ParentComponent {
       @ViewChild(ChildComponent) child;
    
       ngAfterViewInit() {
          console.log('only after THIS EVENT "child" is usable!!');
          this.child.hide();
       }
    }
    

    查看官方文档:https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-view-child

    现场演示plunker:https://plnkr.co/edit/fEYwlKlkMbPdfx9IGXGR?p=preview

  • 1

    要调用孩子的功能,你需要 @ViewChild . 但是,为了显示/隐藏组件,最好在模板中解决此问题:

    <parent>
        <button (click)="showChild=!showChild">Toggle child</button>
        <child *ngIf="showChild"></child>
    </parent>
    

    无需声明自定义函数 hide() .

相关问题