How to call router outlet child component method from parent comonent

前端 未结 10 1982
甜味超标
甜味超标 2020-12-18 19:42

I am new to angular2


    

I have a button in parent component, if

10条回答
  •  暖寄归人
    2020-12-18 20:13

    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");
    

提交回复
热议问题