0
votes

We have the following requirement.

We have a master root layout in the app root component. In this layout we have a router-outlet and components are injected into the router-outlet by using the Angular routing mechanism.

We need to hook from the master root layout into the lifecycle events of the components being injected into the router-outlet.

Because if we register to the router events NavigationEnd it is sometimes being invoked before the component ngOnInit. So we know when the navigation ends but we don't know when the component has finished doing work. Ideally we would like to tap into the lifecycle events of a component.

The requirement is also that the components being injected do not inherit a special class or something like that...

How can this be done?

1

1 Answers

0
votes

Maybe you can create a shared service that you inform when the components you want call in the lifecycle hooks such as ngOnInit, ngOnDestroy etc.

@Injectable({
  providedIn: 'root'
})
export class LifeCycleHookService{
    private hookSubject = new Subject<any>();
    onHookFired = this.hookSubject.asObservable();


    //  component: Component - Reference to the component
    //  hookType: Enum | string - OnInit, OnDestroy etc.
    fireHook = (component, hookType) => {
      this.hookSubject.next({component, hookType});
    }

}

Then in your parent component, you can subscribe to onHookFired of the service.

@Component(
...
)
export class ParentComponent implements OnInit{
   constructor(private hookService: LifeCycleHookService){}

  ngOnInit(){
    this.hookService.onHookFired.subscribe((event) => {
      // event.component
      // event.hookType
    })
  }
}

Then in your child components, you can inform the service on lifecycle hooks.

@Component(
...
)
export class ChildComponent implements OnInit, OnDestroy{
   constructor(private hookService: LifeCycleHookService){}

  ngOnInit(){
    this.hookService.fireHook(this, 'onInit');
  }

  ngOnDestroy(){
    this.hookService.fireHook(this, 'onDestroy');
  }
}

Hope this gives you a hint.