Alon Bi
Alon Bi

Reputation: 83

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 ?

Upvotes: 2

Views: 344

Answers (2)

lealceldeiro
lealceldeiro

Reputation: 15008

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.

Upvotes: 2

Lia
Lia

Reputation: 11982

you can try calling child methods from parent:

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

ts:

getSocketevent() {
    var self = this;
    this.socket.on('data', (data) => {
    this.child.getprod(); // call getprod
      this.notify.emit(data)
    });
  }

Upvotes: 0

Related Questions