在组件之间传递函数

Passing functions between components

我在三个组件之间传递函数时遇到问题。简化后,情况如下所示: 我有一个支持功能的父组件,例如

parent.ts

goToHomePage() { console.log('homepage') }

parent.html

<nb-tabs>
  (actionButton)="goToHomePage()"
</nb-tabs>

然后组件 Tabs 是父子组件,它内部有另一个 TAB 组件,我想将父函数传递给它。

tabs.html

<nb-tab
    [actionButton]="actionButton"
 ></nb-tab>

Tab.html

<div class="tab">
    <button
      (click)="onclick()"
    >Next</button>
  </div>

Tab.ts

  public actionButton: EventEmitter<any> = new EventEmitter<any>();

  onclick(){
    this.actionButton.emit();
  }

然而,它不起作用,我不知道如何通过三个组件(父 -> 子 -> 子)传递函数,目前我只做了两个组件(父 -> 子) .有谁知道如何解决这个问题?

您可以像这样在选项卡和选项卡组件中将 actionButton 声明为 Output()

@Output()
actionButton: EventEmitter<void> = new EventEmitter<void>();

parent.html

<nb-tabs (actionButton)="goToHomePage()"></nb-tabs>

tabs.html

<nb-tab
    (actionButton)="onActionButtonEmitted()"
 ></nb-tab>

tabs.ts

onActionButtonEmitted(): void {
  this.actionButton.emit();
}

Tab.ts

 actionButton: EventEmitter<void> = new EventEmitter<void>();

  onclick(){
    this.actionButton.emit();
  }