Passing Query Parameters and Fragments in Angular 4

–HTML File (servers.component.html)

<a 
  [routerLink]="['/servers', 5, 'edit']"
  [queryParams]="{allowEdit: '1'}"
  fragement="loading"
  href="#"
  class="list-group-item"
  *ngFor="let server of servers">
  {{ server.name }}
</a>

–TS File (Routing)

{path: 'users/:id/:name', component: UserComponent},
{path: 'servers/:id/edit', component: EditServerComponent}

Also with Event ()

–HTML File (home.component.html)

<button class="btn btn-primary" (click)="onLoadServer(1)">Load Server 1</button>

–TS File (home.component.ts)

onLoadServer(id: number) {
  this.router.navigate(['/servers', id, 'edit'], {queryParams: {allowEdit: '1'}, fragment: 'loading'})
}

Destroy Fetching Route Parameters Reactively in Angular 4

–HTML File

<p>User with ID {{user.id}} loaded.</p>
<p>User with is {{user.name}} loaded.</p>
<hr>
<a [routerLink]="['/users', 15, 'Sam']">Load Same (15)</a>

–TS File

import { Component, OnInit, OnDestory } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { Subscription } from 'rxjs/Subscription';

export class UserComponent implements OnInit {
  user: {id: number, name: string};
  paramsSubscription: Subscription;

  constructor(private route: ActivatedRoute){}

  ngOnInit(){
    this.user = {
       id: this.route.snapshot.params['id'],
       name: this.route.snapshot.params['name']
    }
    this.paramsSubscription = this.route.params
      .subscribe(
        (params: Params) => {
             this.user.id = params['id'],
             this.user.name = params['name']
        }
      )
    }

    ngOnDestory(){
       this.paramsSubscription.unsubscribe();
    }
}

–TS File (Routing)

{path: 'users/:id/:name', component: UserComponent}

Fetching Route Parameters Reactively in Angular 4

–HTML File

<p>User with ID {{user.id}} loaded.</p>
<p>User with is {{user.name}} loaded.</p>
<hr>
<a [routerLink]="['/users', 15, 'Sam']">Load Same (15)</a>

–TS File

import { ActivatedRoute, Params } from '@angular/router';

export class UserComponent implements OnInit {
  user: {id: number, name: string};

  constructor(private route: ActivatedRoute){}

  ngOnInit(){
    this.user = {
       id: this.route.snapshot.params['id'],
       name: this.route.snapshot.params['name']
    }
    this.route.params
      .subscribe(
        (params: Params) => {
             this.user.id = params['id'],
             this.user.name = params['name']
        }
      )
    }
}

–TS File (Routing)

{path: 'users/:id/:name', component: UserComponent}

Fetching Route Parameters in Angular 4

–HTML File

<p>User with ID {{user.id}} loaded.</p>
<p>User with is {{user.name}} loaded.</p>

–TS File

import { ActivatedRoute } from '@angular/router';

export class UserComponent implements OnInit {
  user: {id: number, name: string};

  constructor(private route: ActivatedRoute){}

  ngOnInit(){
    this.user = {
       id: this.route.snapshot.params['id'],
       name: this.route.snapshot.params['name']
    }
  }
}

–TS File (Routing)

{path: 'users/:id/:name', component: UserComponent}

Hit URL

http://localhost:4200/users/10/Google

Passing Parameters to Routes in Angular 4

Use Id for this in routing code.

–TS File (app.routing.module.ts)

const appRoutes: Routes = [
  { path: '', component: HomeComponent},
  { path: 'users', component: UserComponent},
  { path: 'users/:id', component: UserComponent},
  { path: 'servers', component: ServersComponent},
    ] },
]

Using Relative Paths in Programmatic Navigation in Angular 4

On click button change navigation with Relative Path in angular 4.

–HTML File

<button (click)="onNewRecipe()">Submit</button>

–TS File

import {Component, OnInit} from "@angular/core";
import { Router, ActivatedRoute } from "@angular/router";

@Component({
  selector: 'app-recipe-list',
  templateUrl: './recipe-list.component.html',
  styleUrls: ['./recipe-list.component.css']
})

export class RecipeListComponent implements OnInit, OnDestroy {
  recipes: Recipe[];
  subscription: Subscription;

  constructor(private router: Router,
              private route: ActivatedRoute) { }

  ngOnInit() {
  }

  onNewRecipe(){
    this.router.navigate(['new'], { relativeTo: this.route});
  }
}

This will be change your page url current to new.

Navigating Programmatically in Anuglar 4

On click button change navigation in angular 4.

–HTML File

<button class="btn btn-primary" (click)="onLoadServers()">Load Servers</button>

–TS File

import { Component, OnInit } from '@angular/core';
import { Router } from "@angular/router";

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  constructor(private router: Router) { }

  ngOnInit() {
  }

  onLoadServers(){
    // complex calculation
    this.router.navigate(['servers']);
  }
}

Private function in Javascript

What is Private function ?

function that we can’t access directly.

–JS

function test () {
   var privatefunction = function () {
       alert('hello');
   }

   return {
       publicfunction : function () {
           privatefunction();
       }
   }
};

Now use it.

var a = test();

a.publicfunction();

This will be call privatefunction.

Child Routing in Angular 4

What is child routing ?

Whenever we want to change inside content of a page beside header footer. So there we need to create a nested router-outlet.

And with this we need to add children attribute in our routing file.


Use there children

–TS File (app-routing.module.ts)

import { NgModule } from "@angular/core";
import { Routes, RouterModule } from "@angular/router";

import { RecipesComponent } from "../recipes/recipes.component";
import { RecipeStartComponent } from "../recipes/recipe-start/recipe-start.component";
import { RecipeDetailComponent } from "../recipes/recipe-detail/recipe-detail.component";
import { RecipeEditComponent } from "../recipes/recipe-edit/recipe-edit.component";

const appRoutes: Routes = [
    { path: '', redirectTo: '/recipes', pathMatch: 'full'},
    { path: 'recipes', component: RecipesComponent, children: [
        { path: '', component: RecipeStartComponent},
        { path: 'new', component: RecipeEditComponent},
        { path: ':id', component: RecipeDetailComponent},
        { path: ':id/edit', component: RecipeEditComponent}
    ] },
]

@NgModule({
    imports: [
        RouterModule.forRoot(appRoutes)
    ],
    exports: [RouterModule]
})

export class AppRoutingModule {}

You can see we have already router-outlet in app.component.html file.

But for child routing we need to add one more router-outlet into recipes.component.html file.

Add new router-outlet in recipes component

<router-outlet></router-outlet>

Use Active Class in Routing in Angular 4

What is Router Active Class in Angular 4 ?

When we want each navigation should have active class, so there we need to use [routerLinkActive] attribute.

–HTML file

<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li routerLinkActive="active"><a routerLink="">Recipes</a></li>
<li routerLinkActive="active"><a routerLink="shopping-list">Shopping List</a></li>
</ul>
</div>
</div>
</nav>

routerLinkActiveOptions in Angular 4

If you are seeing this type navigation home and user both link active. You need to just add one more property routerLinkActiveOptions.

<ul>
<li role="presentation" routerLinkActive="active"><a routerLink="">Home</a></li>
<li role="presentation" routerLinkActive="active"><arouterLink="/servers">Servers</a></li>
<li role="presentation" routerLinkActive="active"><arouterLink="/users">Users</a></li>
</ul>

TO

<ul>
<li role="presentation" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}"><a routerLink="">Home</a></li>
<li role="presentation" routerLinkActive="active"><arouterLink="/servers">Servers</a></li>
<li role="presentation" routerLinkActive="active"><arouterLink="/users">Users</a></li>
</ul>