--- title: 12. Navigation and Routing Additional Techniques tags: Angular Getting Started image: --- # 12. Navigation and Routing Additional Techniques <br/> [toc] <br/> ## Passing parameters to a route <br/> ```app.module.ts //app.module.ts {path: 'products/:id', component: ProductDetailComponent} ``` ```product-list.component.html //product-list.component.html <td> <a [routerLink]="['/products', product.productId]"> {{product.productName}} </a> </td> ``` ```product-detail.component.ts //product-detail.component.ts import { ActivatedRoute } from '@angular/router'; export class ProductDetailComponent implements OnInit{ pageTitle: string = 'Product Detail'; constructor(private route: ActivatedRoute){} ngOnInit(): void{ const id = Number(this.route.snapshot.paramMap.get('id')); this.pageTitle += `: ${id}`; } } ``` **There are two ways to read parameters from a Route** 1. Snapshot: read one time ``` this.route.snapshot.paramMap.get('id'); ``` 2. Observable: read emitted parameters as they change ``` this.route.paramMap.subscribe(params => console.log(params.get('id'))); ``` <br/> ## Prevent null or undefined errors ```product-list.component.html //product-list.component.html {{product?.productName}} ``` another way using *ngIf ```product-list.component.html <div *ngIf='product'> <div>Name:</div> <div>{{product.productName}}</div> </div> ``` <br/> ## Add back buttom to home page ```product-detail.component.ts //product-detail.component.ts import { Router } from '@angular/router'; ... constructor(private router: Router){ onBack(): void{ this.router.navigate(['/products']); } } ``` ```product-detail.component.html //product-detail.component.html <button (click)='onBack()'></button> ``` <br/> ## Build a Guard ```product-detail.guard.ts //product-detail.guard.ts import {Inhectable} from '@angular/core'; import {CanActivate} from '@angular/router'; @Injectable({ provideedIn: 'root' }) export class ProductDetailGuard implements CanActivate { canActivate(): boolean{...} } ``` ```app.module.ts //app.module.ts @NgModel({ imports: [ ..., RouterModule.forRoot([ {path: 'products', component: ProductListComponent}, {path: 'products/:id', canActivate: [ProductDetailGuard], component: ProductDetailComponent }, ...]) ], declarations: [...], bootstrap: [AppComponent] }) export class AppModule{} ``` <br /> ## Protecting Routes with Guard 1. Build a guard service >ng g guard products/product-detail 2. Implement the guard type (CanActivate()) >choose CanActivate 3. Register the guard service provider (Use the providedIn property) \ product-detail.guard.ts ![](https://i.imgur.com/PjDMkeE.png) 4. Add the guard to the desired route