简体   繁体   中英

Angular (4): EventEmitter not working correctly between two components

Here's my application component structure:

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

I'm trying to emit an event when a person presses a button on <action-panel> component, a function should be triggered in the <search> component.

search-component.ts function, which needs to be ran when a button in < action-panel> is pressed.:

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);
  }

}

I've tried putting the (nextButtonEvent)="nextCompany()" into the company component tags, into the <action-panel> tag but it doesn't work. The nextCompany() function of the search-component is never activated.

You can use template referencing variable to call the nextCompany method of search component:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM