Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing event to second level child component

In my Angular 2 ngrx app, I have structure with nested elements:

parentContainer.ts
@Component({
  template: `<parent-component
    (onEvent)="onEvent($event)"
  ></parent-component>`,
})

class ParentContainer {
  constructor(private store: Store<IState>) { }

  private onEvent = (payload: IEventPayload) {
    this.store.dispatch(new EventAction(payload));
  }
}

parentComponent.ts
@Component({
  selector: 'parent-component',
  templateUrl: 'patent.html',
})

class ParentComponent {
  @Output() private onEvent = new EventEmitter<IEventPayload>();
}

patent.html
<div>
  ...some content

  <child-component></child-component>
</div>

In this case, I can emit an event from the parent component, but I need to do it from the child component.

Is there a way to pass an event through a parent component to a child component and then use something like this: this.onEvent.emit({... some payload})?

like image 996
qwe asd Avatar asked Feb 07 '17 13:02

qwe asd


2 Answers

In your patent.html you can let the child-component emit directly through onEvent like this:

<child-component (onChildEvent)="onEvent.emit($event)">
</child-component>
like image 53
amu Avatar answered Oct 11 '22 22:10

amu


In child component:

import { Component, OnInit, EventEmitter, Output } from '@angular/core';

... in class body:

@Output() onMyEvent = new EventEmitter<boolean>();

... call event

this.onMyEvent.emit(true);

In template:

<child-component (onChildEvent)="onEvent.emit($event)">
</child-component>

In parent component:

  onChildEvent(boolean){
    alert("Event now!");
  }
like image 2
mpz Avatar answered Oct 11 '22 22:10

mpz