public

Angular Routing to the same Component

As you may have found out you cannot effectively “route” to the same component more than once and have the same effect as if it were the first time. This

Latest Post Speed kills software engineering. by Matthew Davis public

As you may have found out you cannot effectively “route” to the same component more than once and have the same effect as if it were the first time. This is by design to prevent the routing lifecycle from triggering again.

Do you want to “re-route” to the same component again? You’re in luck! With the combination of a configuration change and listening to the router events you’ll be “re-routing” yourself until the end times.

First we need to use the onSameUrlNavigation property setting the value “reload” for the ExtraOptions argument when calling your RouterModule.forRoot(..).

Setup your router such as:

@NgModule({
    declarations: [

        AppComponent,

        Test1Component,
        Test2Component

    ],
    imports: [

        BrowserModule,
        RouterModule.forRoot([

            {

                path: 'test1',
                component: Test1Component

            }, {

                path: 'test2',
                component: Test2Component

            }

        ], {

            onSameUrlNavigation: 'reload'

        })

    ],
    providers: [],
    bootstrap: [ AppComponent ]
})
export class AppModule {}

Now let’s wire up some test components while subscribing to our router events and watching for NavigationEnd:

TEST1/TEST1.COMPONENT.TS
@Component({
    selector: 'app-test1',
    templateUrl: './test1.component.html',
    styleUrls: [ './test1.component.css' ]
})
export class Test1Component {

    public constructor(private router: Router) {

        this.router.events.subscribe((evt) => {

            if (evt instanceof NavigationEnd) {

                console.log(`${ new Date().toString() }: test1 component routed to`);

            }

        });

    }

}

TEST2/TEST2.COMPONENT.HTML

@Component({
    selector: 'app-test2',
    templateUrl: './test2.component.html',
    styleUrls: [ './test2.component.css' ]
})
export class Test2Component {

    public constructor(private router: Router) {

        this.router.events.subscribe((evt) => {

            if (evt instanceof NavigationEnd) {

                console.log(`${ new Date().toString() }: test2 component routed to`);

            }

        });

    }

}

See Also

Questions, comments or concerns? Contact Me!

Matthew Davis

Published 4 years ago