Passing an event to a second-level child component

In my Angular 2 ngrx application, I have a nested structure:

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 send the event from the parent component, but I need to do this from the child component.

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

+7
source share
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>
+8
source

In the child component:

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

... in the body of the class:

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

... event call

this.onMyEvent.emit(true);

In the template:

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

In the parent component:

  onChildEvent(boolean){
    alert("Event now!");
  }
+2

Source: https://habr.com/ru/post/1669040/


All Articles