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})
?
In your patent.html you can let the child-component emit directly through onEvent like this:
<child-component (onChildEvent)="onEvent.emit($event)">
</child-component>
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!");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With