Angular 2+从其父组件中调用子组件中的函数 [英] Angular 2+ call a function in a child component from its parent component

查看:159
本文介绍了Angular 2+从其父组件中调用子组件中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道执行此操作的最佳方法,以及是否有其他方法.我试图从其父组件中调用子组件中的函数.所以,如果我有

I'd like to know the best way to do this, and if there are different ways. I'm trying to call a function in a child component from its parent component. So if I have:

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

...和child具有称为show()hide()的函数,如何从parent调用这两个函数?

...and child has functions called show() or hide(), how can I call either of those from parent?

推荐答案

在模板内部,使用模板变量/引用:

Inside of your template, using template variables/references:

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

实时演示: https://stackblitz.com/edit/angular-so-3?file=src%2Fapp%2Fapp.component.html

OR

在组件内部:

import { ..., ViewChild, ... } from '@angular/core';

// ...

export class ParentComponent {
   @ViewChild('yourChild' /* #name or Type*/, {static: false}) child;

   ngAfterViewInit() {
      console.log('only after THIS EVENT "child" is usable!!');
      this.child.hide();
   }
}

在组件内部(选项2):

Inside of your component (option2):

import { ..., ViewChild, ... } from '@angular/core';
import { ..., ChildComponent, ... } from '....';

// ...

export class ParentComponent {
   @ViewChild(ChildComponent /* #name or Type*/, {static: false}) 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

这篇关于Angular 2+从其父组件中调用子组件中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆