How to Destroy Active Routing Component from another component in angular

I Have a scenario. My Angular App having 4 components. They Are: AppComponent FirstComponent SecondComponent ThirdComponent.

FirstComponent & Third Component is configured in app-routing.module.ts enter image description here

Now Describing the Scenario: When I am in localhost:4200/first url in browser then I am getting first component. First component Html having a single button.Like below enter image description here

When I click the button the method in ts file toggle a boolean value and on the basis of boolean variable the second component is triggered. Second Component having a text box and a button.Like below enter image description here

Now when I click some text in the text box and hit the button the app redirects to third component and url is localhost:4200/third. Like below

enter image description here enter image description here

Now third component is also having a button. Clicking of the button will toggle 1 boolean value which will render the second component. Like Below enter image description here

Now when I type some name and hit Second Button then according to second component ts file it should redirect to third component which should have single button name third component. (As initializing of third component the boolean value is by default false hence user is not expect to see second component in localhost:4200/third)

But router.navigate is not working. How can I make the routing work from second.component.ts

Kindly Find my Code.

First Component:

enter image description here enter image description here

Second COmponent: enter image description here enter image description here

Third Component: enter image description here enter image description here


Solution 1:

I suppose this is how angular routing works. when you try to navigate to the same URL you currently are, angular ignores the navigation by default. anyhow there is an ExtraOptions object you can specify on angular routing module like described below:

@NgModule({
  imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: 'reload'})],
  exports: [RouterModule]
})
export class AppRoutingModule { }

link to angular documentation

You may think by providing this option, angular resets state of the component (or reloads the page) but this does not work as you want neither. Routing in angular does not primarily re-instantiate your components and it doesn't have to. if you want to do some special work while navigating to the current URL, a workaround is to subscribe to router events. something like this:

  ngOnInit(): void {
    this.router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {
        // do your checks and call your special function/method
      }
    })
  }