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

BBa*_*ger 34 typescript angular

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

<parent>
    <child></child>
</parent>
Run Code Online (Sandbox Code Playgroud)

...并且child具有调用的函数show()或者hide(),如何调用其中任何一个parent

mxi*_*xii 78

在您的模板内:

<parent (click)="yourChild.hide()">
    <child #yourChild></child>
</parent>
Run Code Online (Sandbox Code Playgroud)

在组件内部(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();
   }
}
Run Code Online (Sandbox Code Playgroud)

在您的组件内部(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();
   }
}
Run Code Online (Sandbox Code Playgroud)

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

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

  • 添加了一个demo plunker.如果同一个班级有多个孩子,`ViewChild`将会找到第一个找到的孩子!;) (4认同)
  • 优秀.因此,当将类名传递给@ViewChild时,它会自动获取模板实例化的任何ChildComponent吗? (2认同)
  • 确切地说,我不确定它是第一个还是最后一个如果是多个孩子.但你可以使用`ViewChildren`为多个孩子!使用名称或类的方式相同. (2认同)