In Angular we use routing to separate different parts of our app, generally (but not always) by using the URL to denote our location. Angular’s router is very easy to use.
The idea is that we might put our home page at the URL/home and our About page at /about. In Angular, we’d have a HomeComponent for the /home page and an AboutComponent for the /about page. In the common case, a router lets us map these URLs to a component.
There are three main components that we use to configure routing in Angular:
Routes describes our application’s routes
RouterOutlet is a “placeholder” component that gets expanded to each route’s content
RouterLink is used to link to routes
Let’s create a sample app for routing.
ng new routing-example –-routing
Adding –-routing will add default routing module to the project while creating a project.
In our project, we will create 3 page: home, about, and contact us.
Now let’s generate 3 component for 3 page.
ng g c components/home
ng g c components/about
ng g c components/contactUs
Now we will create a navbar component to navigate through components
ng g c components/navbar
Open app-routing.module.ts. In routes array, we have to map path and components. Let’s map our components.
You can notice here we use the path to specify URL. We specify the component we want to route to using component. We can redirect URL using redirectTo. When user will come to our home page https://localhost:4200 they will implicitly redirect to our home page.
The RouterOutlet directive tells our router where to render the content in the view. Now modify the content of app.component.html as following:
This means, our navbar will be available on all page and in <router-outlet></router-outlet>, the content of the component will be rendered according to URL.
Now open navbar.component.html and write the following markup
As you can see, routerLink link to another component. When the user clicks any of these links, URL will change and desired component will render.
Adding a wildcard route
In our web app, we have many pages and user access them by browsing or directly navigating using URL. Now, what will happen if the user tries to go to https://localhost:4200/abcdefgh ? The user will be redirected to https://localhost:4200 and you will see an error in console. But what if we want to show user an error when users try to access invalid URL?
Generate a new notfound component.
ng g c components/notFound
Now, let’s add this component to routes array.
The ‘**’ match all URL. Now if a user browses any invalid URL, they will be redirected to the notfound component.
You can see that the wildcard route placed at the last route in our routing configuration for it to work as expected. When Angular router matches a request URL to the router configuration, it stops processing as soon as it finds the first match. If you place wildcard route at first of the routing array then the notfound component will always show.