Angular(4):EventEmitter在两个组件之间无法正常工作

时间:2017-09-11 13:26:24

标签: angular

这是我的应用程序组件结构:

<company>
  <search></search>
  <action-panel></action-panel>
</company>

当一个人按下<action-panel>组件上的按钮时,我试图发出一个事件,应该在<search>组件中触发一个功能。

search-component.ts 功能,当按下&lt; action-panel>按钮时需要运行该功能。:

public nextCompany() {
    const currentIndex = this.searchResults.indexOf(this.company);
    this.company = this.searchResults.find(item => this.searchResults.indexOf(item) === currentIndex + 1);
    console.log('Next Company');
    console.log(this.company);
  }

action-panel-component.ts

export class ActionPanelComponent {
  @Output() nextButtonEvent: EventEmitter<any> = new EventEmitter<any>();

  constructor(private companyService: CompanyService) {
  }

  public nextCompany() {
    console.log('pressed next button');
    this.nextButtonEvent.emit(null);
  }

  public deleteCompany() {
    this.companyService.deleteCompany(this.company);
  }

}

我已尝试将(nextButtonEvent)="nextCompany()"放入company组件标记,放入<action-panel>标记,但它不起作用。永远不会激活nextCompany()的{​​{1}}功能。

1 个答案:

答案 0 :(得分:4)

您可以使用模板引用变量来调用搜索组件的nextCompany方法:

<company>
    <search #searchComp></search>
    <action-panel (nextButtonEvent)="searchComp.nextCompany()" ></action-panel>
</company>