2. Agenda
●
●
●
●
●
●
Why routing is necessary
Define routes for pages
Link to Routes
Navigate from Code
Route Based Link Styling
Lazy Loading
3. Why routing is necessary?
● Routing helps in directing users to different
pages based on the option they choose on the
main page. Hence, based on the option they
choose, the required Angular Component will
be rendered to the user.
4. Define routes for pages
●
●
●
Now, before you define routes for pages. Let’s see
<base href>
Most routing applications should add a <base> element to
the index.html as the first child in the <head> tag to tell the
router how to compose navigation URLs.
●
●
●
●
Step 1 − Add the base reference tag in the index.html file.
<html>
<head><base href=”/”></head>
5. Define routes for pages
●
Before we define define routes for the pages, Let’s create files for the
pages.
For example
Let’s create Inventory.component.ts and Product.component.ts and
write simple logic like below
import {Component} from '@angular/core';
@Component ({ selector: 'app-root',template: '<h1>Inventory</h1>'})
export class InventoryComponent {}
6. Link to Routes
● The RouterLink directives on the anchor tags give the
router control over those elements. The navigation paths
are fixed, so you can assign a string to the routerLink (a
"one-time" binding).
That is how you navigate from one page to another
<a routerLink="/product"
routerLinkActive="active">Product</a>
7. Adding an error route
● We can also add an error route. In Routing, one can also add an
error route. This can happen if the user goes to a page which does
not exist in the application.
Step1. Add a PageNotFound component as NotFound.component.ts.
Step2. {path: '**', component: PageNotFoundComponent}
** is for any route which does not fit the default route. They will be
directed to the PageNotFoundComponent component.
8. Navigate from code
●
Of course, You can navigate from page to another using code.
Let’s see How do we do that.
We will need to inject router in the constructor and call navigate
function.
export class TestComponent {constructor(private router:
Router) {}
back() {
this.router.navigate(['/']);}}
9. Route Based Linking Style
●
If you have a header in your website and you want to
highlight the currently active link then you can do that by
using “routerLinkActive”
Step1 . <li><a routerLink="/home"
routerLinkActive="active">Home</a></li>
Step2. Add css
#nav-bar li > a.active {
color: black;
10. Lazy Loading
So far our app has only one module and that is app
module. Let’s see how we can add multiple module.
Our application can be broken down into smaller
sections. We will add in a user module.
●