Monday 19 April 2021

Angular Router ? Components, routes and paths ? Steps to setup basic Routing demo

  • Intro to Angular Router
  • The Components, routes and paths
  • The router outlet
  • The routerLink directive (replaces the href attribute)
  • Steps to setup basic Routing demo
  • Route parameters
  • Query parameters
  • Route guards
  • Feature Module
  • Lazy Loading
  • Route resolvers
Introducing the Angular Router
  • The Angular router is an essential element of the Angular platform. 
  • It allows developers to build Single Page Applications with multiple states and views using routes and components and allows client side navigation and routing between the various components.
Routes and Paths

In Angular, a route is an object (instance of Route) that provides information about which component maps to a specific path. A path is the fragment of a URL that determines where exactly is located the resource (or page) you want to access.

Each route can have the following properties:

Path-: is a string that specifies the path of the route.

pathMatch-: is a string that specifies the matching strategy. It can take prefix (default) or full.
Component-: is a component type that specifies the component that should be mapped to the route.
redirectTo-: is the URL fragment which you will be redirected to if a route is matched.

Ex-: { path: 'my/path/', component: MyComponent }
{ path: '',  redirectTo: '/products', pathMatch: 'full' }

The Router Outlet
The Router-Outlet is a directive exported by RouterModule and acts as a placeholder that indicates to the router where it needs to insert the matched component(s). 

Ex-: <router-outlet></router-outlet>

RouterLink, Navigate and NavigateByUrl
you need to do is to add the navigation links that take you from one component to another.

Angular provides the routerLink and routerLinkActive directives that need to be added to the <a> anchors.

The routerLink directive needs to used instead of the href attribute.
The routerLinkActive directive is used to add a CSS class to an element when the link's route becomes active.
Ex-: <a [routerLink] = "'/products'">
  Go to Products List
</a>

router.navigate(['/‘,’products’])
router.navigateByUrl('/products')

Steps to setup basic Routing

The following command uses the Angular CLI to generate a basic Angular app with an app routing module, called AppRoutingModule, which is an NgModule where you can configure your routes.
New Project
i) ng new routing-app 
    After that it asks for Would you like to add Angular routing? y
ii) ng new routing-app --routing

In Existing Project want to add routing
iii) ng generate module app-routing --module app --flat


//app-routing.module
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router'; 

const routes: Routes = [
{ path: 'first-component', component: FirstComponent }, { path: 'second-component', component: SecondComponent },
{ path: '**', component: PageNotFoundComponent }
]; 
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }





<!--app.component-->
<h1>Angular Router App</h1>
<!-- This nav gives you links to click, which tells the router which route to use (defined in the routes constant in  AppRoutingModule) -->
<nav>
  <ul>
    <li><a routerLink="/first-component" routerLinkActive="active">First Component</a></li>
    <li><a routerLink="/second-component" routerLinkActive="active">Second Component</a></li>
  </ul>
</nav>
<!-- The routed views render in the <router-outlet>-->
<router-outlet></router-outlet>

Route Parameters/Query Parameter
Dynamic routes are often used in web applications to pass data (parameters) or state to the application or between various components and pages. The Angular router has support for dynamic paths and provides an easy to use API to access route parameters.

Ex-: {path: 'product/:id' , component: ProductDetailComponent}

Getting route information

We can get this through ActivatedRoute -Provides access to information about a route associated with a component that is loaded in an outlet. 

Route Parameters/Query Parameter
Dynamic routes are often used in web applications to pass data (parameters) or state to the application or between various components and pages. The Angular router has support for dynamic paths and provides an easy to use API to access route parameters.

Ex-: {path: 'product/:id' , component: ProductDetailComponent}

Getting route information

We can get this through ActivatedRoute -Provides access to information about a route associated with a component that is loaded in an outlet. 

Ex-: Two ways  route parameter 1) this.route.snapshot.paramMap.get('id');
2) this.route.paramMap.pipe( switchMap(params => { this.selectedId = Number(params.get('id'));})
3) this.route.queryParams.subscribe(params => {
        this.param1 = params['param1'];
        this.param2 = params['param2'];
    });
4) this.route.snapshot.params.param1;

Angular Route Guards
Route guards enables you to allow or disallow access to your specific application routes based on some criteria (for example if the user is logged in or not).

Feature modules
A feature module is an organizational best practice, as opposed to a concept of the core Angular API. A feature module delivers a cohesive set of functionality focused on a specific application need such as a user workflow, routing, or forms. While you can do everything within the root module, feature modules help you partition the app into focused areas.

Lazy-loading feature modules

By default, NgModules are eagerly loaded, which means that as soon as the app loads, so do all the NgModules, whether or not they are immediately necessary. For large apps with lots of routes, consider lazy loading—a design pattern that loads NgModules as needed. Lazy loading helps keep initial bundle sizes smaller, which in turn helps decrease load times.


Ex-: Step 1) const routes: Routes = [  {
    path: 'items',
    loadChildren: () => import('./items/items.module').then(m => m.ItemsModule)
  }
];

2) const routes: Routes = [ { path: '', component: CustomersComponent } ]; 
@NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) 
export class CustomersRoutingModule { }
3) @NgModule({
 imports: [ CommonModule, CustomersRoutingModule ], 
declarations: [CustomersComponent] }) 
export class CustomersModule { }

Resolver
To preload component data, we can use a resolver. Resolvers improve UX by blocking the page load until all necessary data is available to fully display the page.

Steps to create
Define Service
export class CrisisDetailResolverService implements Resolve<> {
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<> {
// your logic goes here
}
}

2) Import this resolver into your module's routing module.
{ path: '/your-path', component: YourComponent, resolve: { crisis: YourResolverService } }
3) In the component, use an Observable to get the data from the ActivatedRoute.





No comments:

Post a Comment