I’ve implemented a component reuse strategy in Angular, and I’m applying this functionality when navigating internal back(not browser back button) navigation.
However, after navigating back and clicking on a current list item to move to another component, ngOnInit() is not triggering due to the reuse strategy. How can I ensure ngOnInit() is triggered in this case?
CustomRouteReuseStrategyService
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, DetachedRouteHandle, RouteReuseStrategy } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class CustomRouteReuseStrategyService implements RouteReuseStrategy {
private handlers: { [key: string]: () => void } = {};
private backNavigation: boolean;
setBackNavigation(backNavigation: boolean): void {
this.backNavigation = backNavigation;
}
shouldDetach(route: ActivatedRouteSnapshot): boolean {
return this.backNavigation ? false : true;
}
store(route: ActivatedRouteSnapshot, handler: () => void): void {
this.handlers[route.routeConfig.path] = handler;
}
shouldAttach(route: ActivatedRouteSnapshot): boolean {
return !!this.handlers[route.routeConfig.path];
}
retrieve(route: ActivatedRouteSnapshot): () => void {
return this.handlers[route.routeConfig.path];
}
shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return future.routeConfig === curr.routeConfig;
}
}
back navigation in header component
goBack(): void {
console.log("Go back clicked>>>");
// Set the back navigation flag to true
this.customRouteReuseStrategyService.setBackNavigation(true);
// Navigate back
//this.router.navigate(['../'], { relativeTo: this.route });
//this.location.back();
this.navigationService.goBack();
}
6