Search code examples
angulareventseventemitter

How to call function in component B when I get an event for this function in Component A


I want to use Event Emiter when I get an event from ws:

I have this function that get me events, When I have an event I want to call a function in other component.

Component A, typescript code:

@Output() notify: EventEmitter<any> = new EventEmitter();
getSocketevent() {
  this.socket.on('data', (data) => {
    this.notify.emit(data)
  });
}

Component A, html code:

<app-component-B (click)='getSocketevent()'></app-component-B>

In component B I want to call this function:

getprod() {
  this.ws.getallprod().subscribe(res => {
    this.dataSource = new MatTableDataSource(res);
    this.dataSource.paginator = this.paginator
  })
}

How to call function in component B when I get an event for this function in Component A ?


Solution

  • From Component Interaction > Parent calls an @ViewChild()

    When the parent component class requires that kind of access, inject the child component into the parent as a ViewChild.

    In your case it would be:

    // A component.ts
    ....
    @ViewChild(BComponent, {static: false})
    private bComponent: BComponent;
    
    getSocketevent() {
      this.socket.on('data', (data) => {
        // this.notify.emit(data)
        this.bComponent.getprod();
      });
    }
    

    StackBlitz Demo

    In this case you can see that you don't really need to use an EventEmitter.