Search code examples
angulartypescriptngrx

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


Solution

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

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