Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Router when navigating programatically, old component stays in the dom

Angular version: 4

After signing in from the LoginComponent (located in public/signin route, I want to navigate to TestComponent in the path public/test. I'm doing so as following: this._router.navigate(['public/test']) Then, it redirects correctly but the problem is that it doesn't remove LoginComponent from the DOM (although ngOnDestroy does get called).

It's worth mentioning that navigating to TestComonent using <a routerLink='/public/test'>Test</a> works as expected.

What am I doing wrong?

app.routing.ts:

const APP_ROUTES:Routes = [
  {path: 'public', loadChildren: './authentication/authentication.module#AuthenticationModule'}
];

export const APP_ROUTING:ModuleWithProviders = RouterModule.forRoot(
APP_ROUTES, {
useHash: false, enableTracing: true, initialNavigation: true});

` authentication.routing.ts (where both of these components belong):

const routes: Routes = [
    {
        path: '',
        children: [
            {path: 'test', component: TestComponent},
            {path: 'signin', component: LoginComponent},
        ]
    }
];

export const routing = RouterModule.forChild(routes);
like image 783
Ben Avatar asked Aug 08 '17 10:08

Ben


People also ask

What is the difference between routing and navigation?

The process of defining navigation element and the corresponding view is called Routing. Angular provides a separate module, RouterModule to set up the navigation in the Angular application.

What does the * * path in Angular router do?

The two asterisks, ** , indicate to Angular that this routes definition is a wildcard route. For the component property, you can define any component in your application.

Which defines how the router should navigate to a component based on URL pattern?

An AngularJS component with a RouteConfig and an associated Router. Defines how the router should navigate to a component based on a URL pattern. The directive ( <ng-outlet> ) that marks where the router should display a view.


1 Answers

I have a same problem. I fixed by add this before routing:

this.zone.run(() => {
    // Your router is here
    this._router.navigate(['public/test'])
});
like image 67
Hoang Nguyen Ba Avatar answered Oct 20 '22 13:10

Hoang Nguyen Ba