父组件的angular2调用函数 [英] angular2 call function of parent component

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

问题描述

我有一个应用程序,其中有一个上传组件,可以在其中上传文件.它嵌入在body.component中.

I have an app where I have an upload component where I can upload a file. It is embedded in the body.component.

在上传时,它应使用父组件的功能(例如BodyComponent.thefunction())(调用以更新数据):但前提是父组件特别是body.component.上载可能还会在其他地方以不同的方式使用.

On upload, it should use a function (e.g. BodyComponent.thefunction()) of the parent component (do a call to update the data): but only if it the parent is specifically the body.component. The upload might also be used elsewhere with different behavior.

类似于parent(this).thefunction()的方法,怎么做?

Something like parent(this).thefunction(), how to do that?

推荐答案

我将在子组件中创建一个自定义事件.像这样的东西:

I would create a custom event in the child component. Something like that:

@Component({
  selector: 'child-comp',
  (...)
})
export class ChildComponent {
  @Output()
  uploaded = new EventEmitter<string>();

  uploadComplete() {
    this.uploaded.emit('complete');
  }

您的父组件可以在此事件上注册

Your parent component could register on this event

@Component({
  template `
    <child-comp (uploaded)="someMethod($event)"></child-comp>
  `,
  directives: [ ChildComponent ]
})
export class ParentComponent {
  (...)

  someMethod(event) {
  }
}

另一种方法是将父组件注入子组件中,但是它们将牢固地链接在一起...

Another way would be inject the parent component in the child one but they will be strongly linked together...

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

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