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

瘦欲@ 提交于 2019-12-08 20:57:52

问题


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

回答1:


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

this.zone.run(() => {
    // Your router is here
    this._router.navigate(['public/test'])
});



回答2:


i had the same problem as you and found a (temporary) work around. First i thought it was a routing problem with the lazy loading on a module, i changed to working on the components but the problem never disappeared.

Finally i implemented OnDestroy (from core) in my component. When the ngOnDestroy function is called i wrote a little javascript that removes the resting element from the DOM.

var parent = document.getElementsByTagName("parent-name");
var child = document.getElementsByTagName("ng-component");
parent[0].removeChild(child[0]);

I know this is just a temporay work around but maybe good enough till you get a final answer from someone one this.

Hope




回答3:


Have you tried adding a slash to the beginning so that it exactly matches your routerlink?

this._router.navigate(['/public/test'])

Here is more info on relative vs absolute paths in routes: https://angular.io/guide/router#relative-navigation



来源:https://stackoverflow.com/questions/45566128/angular-router-when-navigating-programatically-old-component-stays-in-the-dom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!