Angular Router Imports

Angular Router Imports

The Angular Router is what makes an Angular Application a Single Page Application, or SPA. For learning all about the benefits of the SPA architecture, have a look at this post.

The first thing that we should do is simply write some routing configuration. What we are doing in this initial configuration is to map certain URL paths to Angular components: meaning that if there is a path match then the component gets displayed:
export const routeConfig:Routes = [
{
path: ‘home’,
component: Home
},
{
path: ‘lessons’,
component: AllLessons
}
];

This configuration means:

if you navigate to /home then the Home component gets displayed
if you navigate to /lessons then AllLessons component gets displayed
and if you navigate elsewhere you are going to get an error

But where do these components get displayed?
Configuring a primary router outlet

Once the router has a URL match, it will try to display the corresponding matching components. for that it will look in the template for a router-outlet component:
@Component({
selector:’app’,
template: `
<main>
<router-outlet></router-outlet>
</main>
`
})
export class App {

}

Router outlet is a dynamic component that the router uses to display in this case either the Home or the AllLessons components. There is nothing special about these components, these could be any component.
Bootstrapping the router

To finish the setup of the router, we also need to add its directives and injectables into the Angular bootstrap system. We do so by importing the RouterModule into the application root module:
import {RouterModule} from “@angular/router”;
import {BrowserModule} from “@angular/platform-browser”;
import {RouterModule} from “@angular/router”;

@NgModule({
declarations: [App],
imports: [BrowserModule, RouterModule.forRoot(routeConfig)],
bootstrap: [App] })
export class AppModule {
}

platformBrowserDynamic().bootstrapModule(AppModule);

Notice that we configure the module by using the forRoot function instead of simply adding the RouterModule. To learn more about why this is necessary, have a look at this other post on @NgModule.

With this, if we access the /home or /lessons URLs, we would get the corresponding component displayed.

But here is where for new users of the router things might start to go wrong.

 

IT Professionals, Web Developers, web programmers, IT students can Apply for the certification course and get ahead.

Angular 4 Tutorial IndexBack to Angular 4 Tutorial Main Page

Angular Routing Basics
Angular Route Configuration

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?