Angular 4-如何在没有EventEmitter的情况下从子组件调用父方法? [英] Angular 4 - How to call parent method from child component without EventEmitter?

查看:204
本文介绍了Angular 4-如何在没有EventEmitter的情况下从子组件调用父方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序具有以下层次结构:

I have following hierarchy in my app:

AppComponent » ThemeComponent » HeaderNavComponent

ThemeComponent有一个方法

The ThemeComponent has a method

   qrIconClicked(){

   }

我需要从HeaderNavComponent调用此方法.

I need to call this method from HeaderNavComponent.

我该怎么办?

推荐答案

您可以通过在子HeaderNavComponent组件中定义@Output类型变量,并在需要时从子对象中定义气泡和事件来实现此目的,父组件ThemeComponent并触发方法qrIconClicked()

You can do that by defining @Output type variable in your child HeaderNavComponent component and bubble and event when you want from the child which will be captured by the parent component ThemeComponent and fire a method qrIconClicked()

所以您的子组件看起来像

So your child component will look like

export class HeaderNavComponent {
   @Output() editDone = new EventEmitter<EditEvent>();

  onSubmit() {
    if (some condition) {
      this.editDone.emit('some value');
    } else {
      this.editDone.emit('other value');
    }
  }
}

当您从子组件中引发editDone事件时,在调用子组件时,您可以分配一个函数,以在该事件发生时调用.

As you raise editDone event from your child component, while calling your child component you can assign a function to call when that event will be emmitted.

<header-nav(editDone)="qrIconClicked($event)"><header-nav>

最后,在传递给父级的事件中,您的函数将从子级获取价值

And finally you function will get value from child in the event passed to parent

   qrIconClicked(event: any){
     //event will hold value from chilld 
   }

这篇关于Angular 4-如何在没有EventEmitter的情况下从子组件调用父方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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