unit_5-angular-routing-and-application-development
unit_5-angular-routing-and-application-development
AppRoutingModule (excerpt)
The Angular CLI performs this step for you. However, if you are creating an application manually or
working with an existing, non-CLI application, verify that the imports and configuration are correct. The
following is the default AppModule using the CLI with the --routing flag.
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule // CLI adds AppRoutingModule to the AppModule's imports array
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
The Angular CLI performs this step automatically. The CLI also sets up a Routes array for your routes
and configures the imports and exports arrays for @NgModule().
CLI application routing module
Each route in this array is a JavaScript object that contains two properties. The first property, path,
defines the URL path for the route.
The second property, component, defines the component Angular should use for the corresponding path.
AppRoutingModule (excerpt)
Now that you have defined your routes, add them to your application. First, add links to the two
components.
Assign the anchor tag that you want to add the route to the routerLink attribute.
Set the value of the attribute to the component to show when a user clicks on each link. Next, update
your component template to include <router-outlet>.
This element informs Angular to update the application view with the component for the selected route.
Route order
The order of routes is important because the Router uses a first-match wins strategy when matching
routes, so more specific routes should be placed above less specific routes.
List routes with a static path first, followed by an empty path route, which matches the default route.
The wildcard route comes last because it matches every URL and the Router selects it only if no other
routes match first.
Getting route information
Often, as a user navigates your application, you want to pass information from one component to
another.
For example, consider an application that displays a shopping list of grocery items.
Each item in the list has a unique id. To edit an item, users click an Edit button, which opens
an EditGroceryItem component. You want that component to retrieve the id for the grocery item so it can
display the right information to the user.
Use a route to pass this type of information to your application components. To do so, you use the with
ComponentInputBinding feature with provide Router or the bindToComponentInputs option
of RouterModule.forRoot.
content_copyproviders: [
provideRouter(appRoutes, withComponentInputBinding()),
]
2. Update the component to have an Input matching the name of the parameter.The component
input (excerpt)
content_copy@Input()
this.hero$ = this.service.getHero(heroId);
NOTE:
You can bind all route data with key, value pairs to component inputs: static or resolved route data,
path parameters, matrix parameters, and query parameters.
Setting up wildcard routes
A well-functioning application should gracefully handle when users attempt to navigate to a part of your
application that does not exist.
To add this functionality to your application, you set up a wildcard route. The Angular router selects this
route any time the requested URL doesn't match any router paths.
To set up a wildcard route, add the following code to your routes definition.
AppRoutingModule (excerpt)
The two asterisks, **, indicate to Angular that this routes definition is a wildcard route.
Prepared By: Department of Computer Engineering Page 4
Subject Name: Modern Practical Tools Unit No: IV Subject Code: 4340705
For the component property, you can define any component in your application.
Common choices include an application-specific PageNotFoundComponent, which you can define
to display a 404 page to your users; or a redirect to your application's main component.
A wildcard route is the last route because it matches any URL. For more detail on why order matters for
routes, see Route order.
To display a 404 page, set up a wildcard route with the component property set to the component you'd
like to use for your 404 page as follows:
AppRoutingModule (excerpt)
];
The last route with the path of ** is a wildcard route. The router selects this route if the requested URL
doesn't match any of the paths earlier in the list and sends the user to the PageNotFoundComponent.
5.2 Common Routing Requirements, Required Route Params, Optional Route Params
Required Parameters
Required Route Parameters is used in pattern matching of the route so syntax should be correct in path .
Prefer This Parameter when value is simple not complex and multiple parameters are not passed
Syntax
//Declaration
const appRoutes:Routes = [{path:employee/:id,component:abcComp}]
// Here id is added as required parameter //Implementation in Ts (typescript)
let id = 2 // It can be dynamic this.route.navigate(['employee',id])// Catching The Route Parameter in Ts
constructor (private route :ActivatedRoute){
}
let id = parseInt(this.route.snapshot.paraMap.get('id'))
Optional Parameter
This Parameter is used when they are optional and we need to pass complex and multiple parameters.
Optional parameter is not used in patter matching so we don’t need it to declare in routing path.
// Declaration
const appRoutes:Routes = [{path:employee,component:abcComp}]
// You dont need to set optional parameter in routing
//Implementationthis.route.navigate(['employee',{name:'ab'}]) // You can add multiple by using
,separated key for example {name:'ab',id:'1'}// Catching constructor (private route :ActivatedRoute){
}
let name = this.route.snapshot.paraMap.get('name')
Query Parameters
They are used to pass complex parameters and they are not used in pattern matching so we don’t need it
to declare in routing path.
// Declaration
const appRoutes:Routes = [{path:employee,component:abcComp}]
// You dont need to set Query parameter in routing// Implementation in Ts
this.route.navigate(['employee'],{queryParams:{name:'a'}})//queryParamsHandling='Merge' or 'retain'
these options is also used to retain the parameters or to merge them // Catching in Ts constructor(private
route :ActivateRoute){
}
let name = this.route.snapshot.queryParamMap.get('name');
NavigationExtras
This New Method Cam After Angular 7.2.0
//Declaration
const appRoutes:Routes = [{path:employee,component:abcComp}]
// You dont need to set Extras in routing//Implementation In Ts
this.route.navigate(['employee'],{state:{name:'A'}})//Catching in Ts constructor (private router :
Router){this.router.getCurrentNavigation().extras.state.name;
}// This works only in constructor it will not work on ngOnInit
5.3 Route Guards: Authenticated-Only Routes, Preventing Unload, Preloading Data Using
Resolve
1. CanActivate
2. CanActivateChild
3. CanDeactivate
4. CanLoad
Please note that all Route guards have interfaces that need to be implemented in the component class.
eg. “CanActivate” is an interface that has a method called “canActivate”
Suppose we have multiple Route guards applied to a specific route then all route guards should return
true to navigate. If any route guard returns false then the navigation will be canceled.
1. MemberAuthGaurd
2. DetailsAuthGuard
So both route guards should return true. In case any of the route guards return false then “member”
navigation will not work.
First, we will see the syntax/command used to create a route guard.
Syntax : ng g g “name of the guard”
Now we will create an angular application and implement RouteGuard to get hands-on experience.
Example
1. Create a new angular application,
2. Create Two components
3. Implement Routing
4. Create a new Auth service.
5. Create RouteGaurd
6. Configure Service in the RouteGuard
7. Configure
o Provider: Declares services that are available to the entire application if it is a root module.
Example of a native root module:
@NgModule({
Announcement: [
AppComponent
],
import: [
browser module,
app routing module
],
Providers: [], //Os service declarados and Propried providers do modulo root ficum disponivism
toda a applicacao
bootstrap: [AppComponent] //define some or module root um bootstrap
})
export class AppModule { }
In the above sample code, we have converted the AppModule class into an Angular module using the
@NgModule decorator.
AppRoutingModule (excerpt)
content_copyconst routes: Routes = [
{
path: 'item',
loadChildren: () => import('./items/items.module').then(m => m.ItemModule)
}
];
Step 1:
Create a new Angular project,
ng new angular-lazy-loading
Step 2:
The purpose of independent routing is to handle all components with Angular lazy-loading modules.
ng g m lazy-loading-routing
Step 3:
Create a component called lazy-demo within the lazy-loading module,
ng g c lazy demode
Step 4:
Adding a link to the header will implement lazy loading.
app.component.html
<li class="nav-item">
<a class="nav-link" [routerLink]="['/lazy-loading']">
slow loading
</a>
</li>
Step 5:
Here we will lazily load the module using load children.
App-routing.module.ts
path: 'lazy-loading',
load children: () => import('./lazy-loading/lazy-loading.module')
.then(m => m.LazyLoadingModule)
},
Step 6:
Set the route in lazy-loading-routing.module.ts.
lazy-loading-routing.module.ts
You will see that main.js is being served upon refreshing the browser. The Lazy Loading module is loaded only
when the root /lazy-loading is hit.