I am new to angular2
I have a button in parent component, if
None of the above solution worked for me in Angular 10. Let me share with you CustomEventHandler service I created to manage this problem:
@Injectable()
export class CustomEventHandler {
private eventHandlersMap: Map = new Map();
constructor() {
}
public callEvent(eventName: string, data?: any): void {
this.eventHandlersMap.get(eventName)(data);
}
public addListener(eventName: string, callback: Function): void {
this.eventHandlersMap.set(eventName, callback);
}
}
You can addListener in child component constructor and call any method in component from parent.
// add listener in child component
this.customEventHandler.addListener("some-event", this.someMethodToCall.bind(this));
// call this in parent component
this.customEventHandler.callEvent("some-event");