如何在angular2中调用另一个组件函数 [英] How to call another components function in angular2

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

问题描述

我有以下两个组件,我想从另一个组件调用一个函数.这两个组件都包含在使用指令的第三个父组件中.

I have two components as follows and I want to call a function from another component. Both components are included in the third parent component using directive.

组件1:

@component(
    selector:'com1'
)
export class com1{
    function1(){...}
}

组件2:

@component(
    selector:'com2'
)
export class com2{
    function2(){...
        // i want to call function 1 from com1 here
    }
}

我尝试使用@input@output,但我不完全了解如何使用它以及如何调用该函数,有人可以帮忙吗?

I've tried using @input and @output but I don't understand exactly how to use it and how to call that function, can anyone help?

推荐答案

如果com1和com2是同级,则可以使用

If com1 and com2 are siblings you can use

@component({
  selector:'com1',
})
export class com1{
  function1(){...}
}

com2使用EventEmitter

@component({
  selector:'com2',
  template: `<button (click)="function2()">click</button>`
)
export class com2{
  @Output() myEvent = new EventEmitter();
  function2(){...
    this.myEvent.emit(null)
  }
}

此处,父组件添加了一个事件绑定以侦听myEvent事件,然后在此类事件发生时调用com1.function1(). #com1是模板变量,允许从模板中的其他位置引用此元素.我们使用它来使function1()com2myEvent的事件处理程序:

Here the parent component adds an event binding to listen to myEvent events and then calls com1.function1() when such an event happens. #com1 is a template variable that allows to refer to this element from elsewhere in the template. We use this to make function1() the event handler for myEvent of com2:

@component({
  selector:'parent',
  template: `<com1 #com1></com1><com2 (myEvent)="com1.function1()"></com2>`
)
export class com2{
}

有关在组件之间进行通信的其他选项,另请参见组件交互

For other options to communicate between components see also component-interaction

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

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