Redirect Path URL to another URL in angular 4

What is Path URL ?

For example this is our domain name

http://localhost:4200

Now I want to redirect it on home url whenever site load.

http://localhost:4200/home

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

const appRoutes: Routes = [
  { path: '', redirectTo:'/home', pathMatch:'full'},
  { path: 'home', component: HomeComponent},
]

Wildcard Routes or 404 page in Angular 4

404 page in angular 4

For that we need to create a component first page404

ng g c page4

–HTML File (page404.component.html)

<h2>Ops something wrong !!</h2>

–TS File (app.component.ts)

const appRoutes: Routes = [
  { path: '', component: HomeComponent},
  { path: 'users', component: UsersComponent, children: [
    { path: ':id/:name', component: UserComponent},
  ]},
  { path: 'servers', component: ServersComponent, children: [
    { path: ':id', component: ServerComponent},
    { path: ':id/edit', component: EditServerComponent},
  ]},
  { path: 'error-404', component: Page404Component},
  { path: '**', redirectTo: '/error-404'}
]

Hit URL

http://localhost:4200/asfdsdf

and You will be redirect to

http://localhost:4200/error-404

queryParamsHandling in Angular 4

–TS File (server.component.ts)

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

import { ServersService } from '../servers.service';

@Component({
  selector: 'app-server',
  templateUrl: './server.component.html',
  styleUrls: ['./server.component.css']
})
export class ServerComponent implements OnInit {
  server: {id: number, name: string, status: string};

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

  ngOnInit() {
    const id = +this.route.snapshot.params['id'];
    this.server = this.serversService.getServer(id);
    this.route.params
      .subscribe(
        (params: Params) => {
          this.server = this.serversService.getServer(+params['id']);          
        }
      )
  }

  onEdit(){
    this.router.navigate(['edit'], {relativeTo: this.route, queryParamsHandling:'preserve'})
  }

}

Using Query Parameters in Angular 4

–HTML File (server.component.html)

<button class="btn btn-primary" (click)="onEdit()">Edit Server</button>

–TS File (server.component.ts)

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

onEdit(){
    this.router.navigate(['edit'], {relativeTo: this.route})
}

–HTML File (edit-server.component.html)

<h4 *ngIf="!allowEdit">You're not allowed to edit!</h4>
<div *ngIf="allowEdit">
<divclass="form-group">
<labelfor="name">Server Name</label>
<input
type="text"
id="name"
class="form-control"
[(ngModel)]="serverName">
</div>
<divclass="form-group">
<labelfor="status">Server Status</label>
<select
id="status"
class="form-control"
[(ngModel)]="serverStatus">
<optionvalue="online">Online</option>
<optionvalue="offline">Offline</option>
</select>
</div>
<button
class="btn btn-primary"
(click)="onUpdateServer()">Update Server</button>
</div>

–TS File (edit-server.component.ts)

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

this.route.queryParams
      .subscribe(
        (queryParams: Params) => {
          this.allowEdit = queryParams['allowEdit'] === '1' ? true : false;
        }
);

Child (Nested) Routes in Angular 4

–TS File

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


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

With children attribute array

–HTML File (servers.component.html)

<div class="col-xs-12 col-sm-4">
<app-edit-server></app-edit-server>
</div>


<div class="col-xs-12 col-sm-4">
<router-outlet></router-outlet>
</div>

Add Dynamically Query Parameters and Fragments in Angular 4

–HTML File (servers.component.html)

<div class="row">
<divclass="col-xs-12 col-sm-4">
<divclass="list-group">
<a
[routerLink]="['/servers', server.id]"
[queryParams]="{allowEdit:'1'}"
fragment="loading"
href="#"
class="list-group-item"
*ngFor="let server of servers">
{{ server.name }}
</a>
</div>
</div>
<divclass="col-xs-12 col-sm-4">
<app-edit-server></app-edit-server>
<hr>
</div>
</div>

–TS File (server.component.ts)

Yes this is nested component of servers.

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

import { ServersService } from '../servers.service';

@Component({
  selector: 'app-server',
  templateUrl: './server.component.html',
  styleUrls: ['./server.component.css']
})
export class ServerComponent implements OnInit {
  server: {id: number, name: string, status: string};

  constructor(private serversService: ServersService,
              private route: ActivatedRoute) { }

  ngOnInit() {
    const id = +this.route.snapshot.params['id'];
    this.server = this.serversService.getServer(id);
    this.route.params
      .subscribe(
        (params: Params) => {
          this.server = this.serversService.getServer(+params['id']);          
        }
      )
  }

}

ngForOf in Angular 4

ngForOf is same as ngFor

But Difference is:-

ngFor = is not type safe
ngForOf = is type safe

How to Use ngFor

Now ngForOf

this will be work with ng-template or template tag only

–HTML

<ng-template ngFor let-user [ngForOf]="users">
<p>{{user.name}}</p>
</ng-template>

Retrieving Query Parameters and Fragments in Angular 4

Retrieving Query Parameters and Fragments in Angular 4

–TS File (edit-server.component.ts)

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

import { ServersService } from '../servers.service';

@Component({
  selector: 'app-edit-server',
  templateUrl: './edit-server.component.html',
  styleUrls: ['./edit-server.component.css']
})
export class EditServerComponent implements OnInit {
  server: {id: number, name: string, status: string};
  serverName = '';
  serverStatus = '';

  constructor(private serversService: ServersService,
              private route: ActivatedRoute) { }

  ngOnInit() {
    console.log(this.route.snapshot.queryParams);
    console.log(this.route.snapshot.fragment);
    this.server = this.serversService.getServer(1);
    this.serverName = this.server.name;
    this.serverStatus = this.server.status;
  }

  onUpdateServer() {
    this.serversService.updateServer(this.server.id, {name: this.serverName, status: this.serverStatus});
  }

}

angular 4 command

Install NPM

{npm install}

Start NPM

{npm start}

NPM tsc

{npm run tsc -w}

install bootstrap

{npm install --save bootstrap@3}

install bower

{npm install -g bower}

install bower(bootstrap)

{bower install bootstarp --save}

Helper library auth

{npm install angular2-jwt --save}

auth0-lock

{npm install auth0-lock --save}

create Service

{ng g s logging}

Install Angular-cli

{npm install -g angular-cli}

Uninstall Angular-cli

{npm uninstall -g angular-cli}

Create new project

{ng new project}

Create new Project with prefix

{ng new recipe-book --prefix rb}

Start Cli

{ng serve}

Start Cli with new port

{ng serve --port 4300}

Create new component

{ng generate component home}
{ng g c directory}

Create component without test file

{ng g c recipes --spec false}

Create component in sub folder

{ng g c recipes/recipes-list --spec false}

Create only ts file with inline

{ng g c another --flat --is --it}

Add the AppRoutingModule

{ng generate module app-routing --flat --module=app}

To disable warning

{{ng set --global}}

Create pipe

{ng g pipe filter}

Create service

{ng g s logging}

Create class

{ng g cl recipe}

Create custom directive

{ng g d highlight}

Install Bootstrap

{npm install --save bootstrap}

after install bootstrap add link to angular-cli.json.

{"../node_modules/bootstrap/dist/css/bootstrap.min.css",}

Build app

{ng build --prod --aot}

CLI version

{ng --version}

Install Firebase

{npm install --save firebase}
{npm install promise-polyfill --save-exact}

Uninstall and Install npm angular cli already done folder

npm unistall --save-dev angular-cli
npm install --save-dev @angular/cli@latest

Sum function parameter and invoke in Javascript

Create sum function with parameter

There we won’t know how much parameter will be there ?

function sum(x){
  if(arguments.length == 1){
    return arguments[0]
  } else if(arguments.length == 2){
    return arguments[0] + arguments[1];
  } else if(arguments.length == 3){
    return arguments[0] + arguments[1] + arguments[2] 
  }
}

//1st Time
console.log(sum(5));
//2nd Time
console.log(sum(5,7));
//3rd Time
console.log(sum(5,7,8));

Now With two Invoke

function sum(x){
  return function(y){
    return x + y
  }
}

console.log(sum(5)(7));