加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何在角度2中调用另一个组件函数

发布时间:2020-12-17 07:46:00 所属栏目:安全 来源:网络整理
导读:我有两个组件如下,我想从另一个组件调用一个函数.这两个组件都使用指令包含在第三个父组件中. 组件1: @component(selector:'com1')export class com1{function1(){...}} 组件2: @component(selector:'com2')export class com2{function2(){...// i want to
我有两个组件如下,我想从另一个组件调用一个函数.这两个组件都使用指令包含在第三个父组件中.

组件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,但我不明白如何使用它,如何调用该功能,任何人都可以帮助?

如果com1和com2是兄弟姐妹,可以使用
@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是一个模板变量,允许从模板中的其他位置引用该元素.我们使用它来make1()com2的myEvent的事件处理程序:

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

有关组件之间通信的其他选项,请参见https://angular.io/docs/ts/latest/cookbook/component-communication.html

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读