Saturday 30 March 2019

NG7 - Gird view toggle List view - Full Design - css and- html

 NG7 -  Gird view toggle List view - Full Design
 ====================================
 COMPONENT.TS
 =============

 export class AngularComponent implements OnInit {

  displayMode=1;
  constructor() { }

  ngOnInit() {
  }

    // List View
   listView() {
     this.displayMode = 2;
  }

    // Grid View
   gridView() {
     this.displayMode = 1;
  }

 }

 template.html
 =================


<p>Switch to list view or grid view.</p>

<div id="btnContainer">
  <button  [ngClass]="{'btn-active': displayMode === 1, 'btn':displayMode === 2}" (click)="listView()"><i class="fa fa-bars"></i> List</button>
  <button  [ngClass]="{'btn-active': displayMode === 2, 'btn':displayMode === 1}" (click)="gridView()"><i class="fa fa-th-large"></i> Grid</button>
</div>

<div class="row">
  <div [ngClass]="{'grid':displayMode === 1, 'list':displayMode !=1}" >
    <div class="title">
      <span class="pull-left">1.Angular Introdution </span>
      <span class="pull-right" routerLink="/angular-intro"> &#10233; </span>
    </div>
    <div class="content">
      <b>What is Angular?</b>
      <p>
      Angular is a platform that makes it easy to build applications with the web. Angular combines declarative templates, dependency injection,
  end to end tooling, and integrated best practices to solve development challenges.
      Angular empowers developers to build applications that live on the web, mobile, or the desktop.</p>
    </div>
  </div>
  <div [ngClass]="{'grid':displayMode === 1, 'list':displayMode !=1}" >
      <div class="title">
        <span class="pull-left">2. Components & Modules </span>
        <span class="pull-right" routerLink="/modules-components"> &#10233; </span>
      </div>
      <div class="content">
      <div class="parent">
        <div class="front">
         <b>Module</b>
          <p><b>@NgModule</b></p>
          <p>Every Angular app has a root module, conventionally named AppModule, which provides the bootstrap mechanism that launches the application. An app typically contains many functional modules.</p>
        </div>
        <div class="back">
          <b>Component</b>
          <p><b> @Component()</b></p>
          <p>Every Angular application has at least one component, the root component that connects a component hierarchy with the page document object model (DOM).
  Each component defines a class that contains application data and logic, and is associated with an HTML template that defines a view to be displayed in a target environment.
           </p>
        </div>
      </div>
    </div>
  </div>
  <div [ngClass]="{'grid':displayMode === 1, 'list':displayMode !=1}" >
    <div class="title">
      <span class="pull-left">3. Forms & Bindings</span>
      <span class="pull-right" routerLink="/forms-binding"> &#10233; </span>
    </div>
    <div class="content">
        <div class="view scard1">
          <div class="frontText">
            <b>Introduction to forms in Angular</b>
            <p> Handling user input with forms is the cornerstone of many common applications. Applications use forms to enable users to log in, to update a profile, to enter sensitive information,
and to perform many other data-entry tasks.</p>
            <p>[Data Binding], (Event Binding), [(Two Way binding)] - Deprecated</p>
          </div>
          <div class="mask">
            <p><b>Reactive forms</b> are more robust: they're more scalable, reusable, and testable. If forms are a key part of your application, or you're already using reactive patterns for building your application,
use reactive forms.</p>
            <p><b>Template-driven</b> forms are useful for adding a simple form to an app, such as an email list signup form. They're easy to add to an app, but they don't scale as well as reactive forms.
If you have very basic form requirements and logic that can be managed solely in the template, use template-driven forms.</p>
          </div>

        </div>
    </div>
  </div>
</div>


....... continue the <div class="row" for multiple rows



STYLE.LESS
=============

* {
  box-sizing: border-box;
}


.grid {
  float: left;
  width: 31.8%;
  height: 24vh;
  margin: 0.5% 0.6%;
  //background: #ccc;
//  border: 1px solid #ccc;
  box-shadow:         1px 1px 2px 3px grey;
  .title{
    padding:10px;
    height:15%;
    font-weight: bold;
    background: #2282fb;
    color: #fff;
  }
  .content{
    padding:10px;
    height:85%;
    overflow-y:auto;
    text-align: justify;
  }
}

.list {
  float: left;
  width: 100%;
  padding: 10px;
  margin: 4px 8px;
  background: #e4e2e2;
  border: 1px solid #ccc;
}

/* Clear floats after the columns */
.row:after {
  content: "";
  display: table;
  clear: both;
}
/* Style the buttons */
.btn {
  padding: 12px 16px;
  background-color: #666;
  cursor: pointer;
}



.btn-active {
  padding: 12px 16px;
  background-color: #f1f1f1;
}

///////////////////////////////////
.parent {
  transition: transform 1s ease-in-out 0s;
  transform-style: preserve-3d;
  width: 100%;
}
.parent:hover {
  transform: rotateY(180deg);
}
.back,
.front {
  width: 100%;
  height: 170px;
  position: absolute;
  top: 0;
  left: 0;
  backface-visibility: hidden;
}
.front {
  background-color: #f1f1f1;
}
.back {
  background-color: #fff;
  transform: rotateY(180deg);
}

.list .parent{
  display: none;
}

////////////////////////
// using less preprocessor the css prob is used
.view {
  width: 100%;
  height: 100%;
  margin:0px 0px 0px 0px;
  float: left;
  overflow: hidden;
  position: relative;

  //-webkit-box-shadow: 1px 1px 2px #e6e6e6;
  //-moz-box-shadow: 1px 1px 2px #e6e6e6;
  //box-shadow: 1px 1px 2px #e6e6e6;
  cursor: default;
  background: #fff;
  border: thin solid #ccc;
  //background: #fff url(avatar.png) no-repeat center center;
}
.scard1{
  background:#f1f1f1;
}
.scard2{
  background:#E8892B;
}
.scard3{
  background:#EB2A47;
}
.scard4{
  background:#27699A;
}

.view .mask {
  width: 100%;
  height: 98%;
  // border:thin solid #0f2d51;
  position: absolute;
  overflow: hidden;
  top: 0;
  left: 0;
  text-align: justify;
  background-color: #fff;
  -webkit-transform: translateY(-200px);
  -moz-transform: translateY(-200px);
  -o-transform: translateY(-200px);
  -ms-transform: translateY(-200px);
  transform: translateY(-200px);
  -ms-filter: "progid: DXImageTransform.Microsoft.Alpha(Opacity=100)";
  filter: alpha(opacity=100);
  opacity: 1;
  -webkit-transition: all 0.7s ease-in-out;
  -moz-transition: all 0.7s ease-in-out;
  -o-transition: all 0.7s ease-in-out;
  -ms-transition: all 0.7s ease-in-out;
  transition: all 0.7s ease-in-out;
}
.view .frontText {
  display: block;
  position: relative;
  -webkit-transition: all 0.7s ease-in-out;
  -moz-transition: all 0.7s ease-in-out;
  -o-transition: all 0.7s ease-in-out;
  -ms-transition: all 0.7s ease-in-out;
  transition: all 0.7s ease-in-out;
}
.frontText{
  h5,h2{
    color:#333;
  }

}
.view:hover .mask {
  -webkit-transform: translateY(0px);
  -moz-transform: translateY(0px);
  -o-transform: translateY(0px);
  -ms-transform: translateY(0px);
  transform: translateY(0px);
}
.view:hover .frontText {
  -webkit-transform: translateY(200px);
  -moz-transform: translateY(200px);
  -o-transform: translateY(200px);
  -ms-transform: translateY(200px);
  transform: translateY(200px);
}
.score-cards{
  .single-card{
    padding:0px;

  }
}
.frontText{
  padding: 1rem;
}

.list .view{
  display: none;
}
b{
  color:brown;
  background: yellow;
}

NG7 - Sanitize HTML in Angular Template

NG7 - Sanitize HTML in Angular Template
================================

import {Component, Input, OnInit} from '@angular/core';
import {DomSanitizer, SafeHtml} from '@angular/platform-browser'

@Component({
 
    selector: 'iframebasedHTML', 
    template: `
      <main>
<div>
<iframe class="embed-responsive-item" [srcdoc]="externFullHtml" allowfullscreen></iframe>
</div>         
      </main>
  `
})

export class ExternHTMLComponent implements OnInit{

    extHtml: SafeHtml;
externFullHtml = `
<html>
<meta charset="utf-8">
<head>
</head>
<body>

<div id="fixedContent">

<span> left content </span>
<span> right content </span>

</div>
</body>
</html>`;


    constructor( private sanitized: DomSanitizer) {}

    ngOnInit() {
this.extHtml = this.sanitized.bypassSecurityTrustHtml(this.externFullHtml);
    }

}

Tuesday 12 March 2019

Ng7- Github pages + angular - How to Deploy an Angular Application to GitHub


Ng7- Github pages + angular - How to Deploy an Angular Application to GitHub

------------------------------------------------------------------------------------

Soln:3 -  Angular version 11
====
Commands which I using in Tutorial Angular version 11 - on 23-mar-2022
1. npm install -g angular-cli-ghpages. 2. ng build --base-href "https://username.github.io/project-name/
". 3. ngh --dir dist/project-name

Change the index.html
<base href="/" /> replace with "https://username.github.io/project-name/"

<base href="https://gnganapath.github.io/AngularGuide/">

goto github -> settings -> pages -> you can see the url is deploy in github pages. change the branch names as well. 

instead of root -> docs will work


Step 1
To create a project using Angular CLI, run the command:

ng new demo

You need to make sure that Angular CLI is installed globally on your machine.

Step 2
Change the directory to demo and open the project in VS Code or any other IDE of your choice.

step 3
ng serve


step 4

Make sure ng build --prod is working or not.  - dist folder creation with
To deploy your Angular application, first create a repository on GitHub. To do that navigate, to https://github.com/

create github repository Name "PROJECT_NAME"

To do that, run the  below command:

git remote add origin https://github.com/USERNAME/PROJECT_NAME.git


step:5

To deploy the Angular application to GitHub, you need to first globally install the angular-cli-ghpages:

npm install -g angular-cli-ghpages

After installing ghpages, use Angular CLI to build the project. For that, run the command as shown below:

 ng build --prod --base-href https://USERNAME.github.io/PROJECT_NAME/

step:6

For the last step, run the command "ngh -no-silent" to publish the application

Soln:2
======
Deploying angular project to GitHub pages is simple and easy.

I assume that you already have a working Angular app ready to be hosted
to GitHub pages and I also assume that you pushed the local repository to Github.
If not, click the below link to follow the instructions for adding an existing angular project to Github.

Step4: in Detail ==>Putting your existing work on GitHub
-----------------

1.Create a new repository on GitHub. To avoid errors, *******=>do not initialize the new repository with README, license, or gitignore files.
You can add these files after your project has been pushed to GitHub.

Open Git Bash.

Change the current working directory to your local project.

2.Initialize the local directory as a Git repository.

$ git init
Add the files in your new local repository. This stages them for the first commit.

3.$ git add .
# Adds the files in the local repository and stages them for commit. To unstage a file, use 'github

Commit the files that you've staged in your local repository.

4.$ git commit -m "First commit"
# Commits the tracked changes and prepares them to be pushed to a remote repository. To remove this commit and modify the file, use 'git reset --soft HEAD~1' and commit and add the file again.
At the top of your GitHub repository's Quick Setup page, click  to copy the remote repository URL. [ it will avail in clone green button to show the github repo url]

In the Command prompt, add the URL for the remote repository where your local repository will be pushed.

5.$ git remote add origin (remote repository URL)
# Sets the new remote
$ git remote -v
6.# Verifies the new remote URL
Push the changes in your local repository to GitHub.

7.$ git push origin master
# Pushes the changes in your local repository up to the remote repository you specified as the origin

8. If any git remote push error
$git pull origin master
git status
git commit
git push origin master

9 ***********important
If you want create remote new branch

create branch in local repo
git checkout -b "branchName"

then git push origin branchName

It will create new branch in github.

Summary: github pages can create a new branch when we do  ->

npm install the angular-cli-ghpages
ng build --prod --base-href https://USERNAME.github.io/PROJECT_NAME/
ngh -no-silent

REf: https://dzone.com/articles/how-to-deploy-an-angular-application-to-github
https://medium.com/@swarnakishore/deploying-angular-cli-project-to-github-pages-db49246598a1 <- soln2
https://help.github.com/en/articles/adding-an-existing-project-to-github-using-the-command-line




Monday 11 March 2019

NG7 How To Update Angular CLI To Version 7, and CLI 7.2.0

How To Update Angular CLI To Version 7
==========================================

You can check your current version of Angular CLI using the following command.

ng --version
To update the latest angular-cli package installed globally in your system, you need to run the following commands.
sudo npm uninstall -g angular-cli // For Mac

npm uninstall -g angular-cli // For Windows Open Powershell on Administrator Mode
It will uninstall the angular-cli package globally from your computer or server.

Then we need to clear the cache using the following command.

sudo npm cache verify
If your npm version is < 5, then you need to hit the following command.

npm cache clean
Now, install the Angular CLI using the following command.

sudo npm install -g @angular/cli@latest
If your version is still old, then try the following command.

ng update @angular/cli
Now, check your Angular CLI version using the following command.

ng --version

After updating both the global and local package, clear the cache to avoid errors:

npm cache verify (recommended)
npm cache clean (for older npm versions)
#Update Angular Packages
Now you need to update the core packages/dependencies to Angular 7. Just run the following command:

project$ng update @angular/cli -> will convert the ng2,4,5-cli.json file into angular.json file. ng6,7....

ng update @angular/core
Upgrading RxJS
You can update RxJS using the ng update command:

ng update rxjs
Generating and serving an Angular project via a development server Create and run a new project:

ng new my-project
cd my-project
ng serve

Ref: https://appdividend.com/2018/10/20/how-to-update-angular-cli-to-version-7/

=====================

Upgrade to Angular 7 -— Within 10 Minutes
===============================================

Everything you need to upgrade

Angular dependencies
====================
npm install @angular/animations@latest @angular/common@latest @angular/compiler@latest @angular/core@latest @angular/forms@latest @angular/http@latest @angular/platform-browser@latest @angular/platform-browser-dynamic@latest @angular/platform-server@latest @angular/router@latest --save


Angular dev dependencies
=========================
npm install @angular-devkit/build-angular@latest @angular/compiler-cli@latest @angular/cli@latest @angular/language-service@latest --save-dev

Dependencies; Core-js and Zone.js
==================================
npm install core-js@latest zone.js@latest --save

Dev dependencies; Types, codelyzer, karma tools, jasmine, protractor and tslint
================================================================================
npm install @types/jasmine@latest @types/node@latest codelyzer@latest karma@latest karma-chrome-launcher@latest karma-cli@latest karma-jasmine@latest karma-jasmine-html-reporter@latest jasmine-core@latest jasmine-spec-reporter@latest protractor@latest tslint@latest --save-dev

The new version 3+ of TypeScript
================================
npm install typescript@latest --save-dev

Latest version 6+ of RxJS
=========================
npm install rxjs@latest rxjs-compat@latest --save
And:

npm install rxjs-tslint@latest --save-dev

Latest version 4+ of Webpack
============================
npm install webpack@latest --save-dev

Enable Ivy Renderer
====================
In your tsconfig.json file add:

"angularCompilerOptions": {
  "enableIvy": true
}

Ref: https://medium.com/@jeroenouw/upgrade-to-angular-7-beta-within-10-minutes-c14fc380edd

Ng7 - GoJs npm better visualization chart better than D3

Ng7 - GoJs npm better visualization chart better than D3

----------------------------         -----------------------------



npm install gojs --save

it will install gojs version 2.0.0 latest in mar2019

no need to add anything in module

component.html
---------------
<div #myDiagramDiv style="width:100%; height:450px; background-color: #DAE4E4;"></div>

component.ts
-----------------

import { Component, OnInit, AfterViewInit,ViewChild, ElementRef, Input, Output, EventEmitter} from '@angular/core';
import * as go from 'gojs';
import { GuidedDraggingTool } from 'gojs/extensionsTS/GuidedDraggingTool';
@Component({
  selector: 'chart-main',
  templateUrl: './main.component.html',
  styleUrls: ['./main.component.less']
})
export class MainComponent implements  OnInit, AfterViewInit {

ngOnInit(){
}

@ViewChild('myDiagramDiv') div;
   ngAfterViewInit(){
    // create a make type from go namespace and assign it to MAKE
    const MAKE = go.GraphObject.make;

    // get the div in the HTML file
    const diagramDiv = this.div.nativeElement;

    // instatiate MAKE with Diagram type and the diagramDiv
    const myDiagram = MAKE(go.Diagram, diagramDiv,  // create a Diagram for the DIV HTML element
      {
        initialAutoScale: go.Diagram.Uniform,  // an initial automatic zoom-to-fit
        contentAlignment: go.Spot.Center,  // align document to the center of the viewport
        layout:
          MAKE(go.ForceDirectedLayout,  // automatically spread nodes apart
            { maxIterations: 200, defaultSpringLength: 30, defaultElectricalCharge: 100 })
      });
  // define each Node's appearance
  myDiagram.nodeTemplate =
    MAKE(go.Node, "Auto",  // the whole node panel
      { locationSpot: go.Spot.Center },
      // define the node's outer shape, which will surround the TextBlock
      MAKE(go.Shape, "Rectangle",
        { fill: MAKE(go.Brush, "Linear", { 0: "rgb(254, 201, 0)", 1: "rgb(254, 162, 0)" }), stroke: "black" }),
      MAKE(go.TextBlock,
        { font: "bold 10pt helvetica, bold arial, sans-serif", margin: 4 },
        new go.Binding("text", "text"))
    );
  // replace the default Link template in the linkTemplateMap
  myDiagram.linkTemplate =
    MAKE(go.Link,  // the whole link panel
      MAKE(go.Shape,  // the link shape
        { stroke: "black" }),
      MAKE(go.Shape,  // the arrowhead
        { toArrow: "standard", stroke: null }),
      MAKE(go.Panel, "Auto",
        MAKE(go.Shape,  // the label background, which becomes transparent around the edges
          { fill: MAKE(go.Brush, "Radial", { 0: "rgb(240, 240, 240)", 0.3: "rgb(240, 240, 240)", 1: "rgba(240, 240, 240, 0)" }),
            stroke: null }),
        MAKE(go.TextBlock,  // the label text
          { textAlign: "center",
            font: "10pt helvetica, arial, sans-serif",
            stroke: "#555555",
            margin: 4 },
          new go.Binding("text", "text"))
      )
    );
  // create the model for the concept map
  var nodeDataArray = [
    { key: 1, text: "Concept Maps" },
    { key: 2, text: "Organized Knowledge" },
    { key: 3, text: "Context Dependent" },
    { key: 4, text: "Concepts" },
    { key: 5, text: "Propositions" },
    { key: 6, text: "Associated Feelings or Affect" },
    { key: 7, text: "Perceived Regularities" },
    { key: 8, text: "Labeled" },
    { key: 9, text: "Hierarchically Structured" },
    { key: 10, text: "Effective Teaching" },
    { key: 11, text: "Crosslinks" },
    { key: 12, text: "Effective Learning" },
    { key: 13, text: "Events (Happenings)" },
    { key: 14, text: "Objects (Things)" },
    { key: 15, text: "Symbols" },
    { key: 16, text: "Words" },
    { key: 17, text: "Creativity" },
    { key: 18, text: "Interrelationships" },
    { key: 19, text: "Infants" },
    { key: 20, text: "Different Map Segments" }
  ];
  var linkDataArray = [
    { from: 1, to: 2, text: "represent" },
    { from: 2, to: 3, text: "is" },
    { from: 2, to: 4, text: "is" },
    { from: 2, to: 5, text: "is" },
    { from: 2, to: 6, text: "includes" },
    { from: 2, to: 10, text: "necessary\nfor" },
    { from: 2, to: 12, text: "necessary\nfor" },
    { from: 4, to: 5, text: "combine\nto form" },
    { from: 4, to: 6, text: "include" },
    { from: 4, to: 7, text: "are" },
    { from: 4, to: 8, text: "are" },
    { from: 4, to: 9, text: "are" },
    { from: 5, to: 9, text: "are" },
    { from: 5, to: 11, text: "may be" },
    { from: 7, to: 13, text: "in" },
    { from: 7, to: 14, text: "in" },
    { from: 7, to: 19, text: "begin\nwith" },
    { from: 8, to: 15, text: "with" },
    { from: 8, to: 16, text: "with" },
    { from: 9, to: 17, text: "aids" },
    { from: 11, to: 18, text: "show" },
    { from: 12, to: 19, text: "begins\nwith" },
    { from: 17, to: 18, text: "needed\nto see" },
    { from: 18, to: 20, text: "between" }
  ];
  myDiagram.model = new go.GraphLinksModel(nodeDataArray, linkDataArray);

}
}

Monday 4 February 2019

NG7- Role based access the application -Auth gurad and CanActivate

Ng7- NGXPermission  - Role Based app access
----------------------------------------------

To install this library, run:
$ npm install ngx-permissions --save

and then from your Angular AppModule:
// Import your library
import { NgxPermissionsModule } from 'ngx-permissions';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,

    // Specify your library as an import
     NgxPermissionsModule.forRoot()
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

SharedModule
--------------
If you use a SharedModule that you import in multiple other feature modules, you can export the NgxPermissionsModule to make sure you don't have to import it in every module.
@NgModule({
    exports: [
        CommonModule,
        NgxPermissionsModule
    ]
})
export class SharedModule { }

Lazy loaded modules
--------------------
When you lazy load a module, you should use the forChild static method to import the NgxPermissionsModule
@NgModule({
    imports: [
        NgxPermissionsModule.forChild({
        permissionsIsolate: true,
        rolesIsolate: true})
    ]
})
export class LazyIsolatedLoadedModule { }

using in component
------------------
import { Component, OnInit } from '@angular/core';
import { NgxPermissionsService } from 'ngx-permissions';

 constructor(private permissionsService: NgxPermissionsService,
               private http: HttpClient) {}

  ngOnInit(): void {
    const perm = ["ADMIN", "EDITOR"];

    this.permissionsService.loadPermissions(perm);
 
     this.http.get('url').subscribe((permissions) => {
       //const perm = ["ADMIN", "EDITOR"]; example of permissions
       this.permissionsService.loadPermissions(permissions);
    })
  }

  Usage in templates
------------------------
<div *ngxPermissionsOnly="['ADMIN', 'GUEST']">
    <div>You can see this text congrats</div>
</div>

<ng-template ngxPermissionsOnly="ADMIN">
  <div>You can see this text congrats</div>
 </ng-template>

 <ng-template [ngxPermissionsExcept]="['JOHNY']">
   <div> All will see it except JOHNY</div>
 </ng-template>


 App-routing.module.ts
 ======================
 lazy module with autguard
 --------------------------->>>
  { path:'admin',canActivate: [AuthGuard],canLoad: [NgxPermissionsGuard],
                data: {
                  permissions: {
                    only: ['SUPER_ADMIN','ADMIN',],
                    redirectTo: '/'
                  }
                }, loadChildren:'./lazymodule/lazymodule.module#LazyModule'  },

 lazy module and inside component
 ---------------------------->>>>
const routes: Routes = [
  {
    path: '', component: lazymoduleComponentComponent,canActivateChild: [NgxPermissionsGuard],
    children: [{
        path: '',component: LazymoduleComponent,
        data: {
          permissions: { 'ROLE_DEVELOPER', 'ROLE_INFORMATIONOWNER', 'ROLE_ADMINISTRATOR', 'ROLE_DELEGATEINFORMATIONOWNER'],
            redirectTo: '/'
          },
        }
      },

  FOR THIS
  IMPORT in import part of module [,...NgxPermissionsModule.forChild(),..], add in providers [NgxPermissionsService]

  import { NgxPermissionsModule } from "ngx-permissions";
import { NgxPermissionsService } from 'ngx-permissions';

///// IMportant:
To load the user roles from Global Service - > loadService or Authguard service or initGetToken service
--------------------------------------------------------------------------------------------------------
import { NgxPermissionsService } from 'ngx-permissions';
@injectable {
export class AuthService

 constructor( private permissionsService: NgxPermissionsService){

 this.permissionsService.loadPermissions(response.Roles);
 }
 }
 REf: https://www.npmjs.com/package/ngx-permissions

Thursday 10 January 2019

Ng6- HttpInterceptors - authroization token in API

Ng5- HttpInterceptors - authroization token in API
------------------------------------------------------------
Method: 1
=========
Angular Interceptors:-
Interceptors are the mechanism where we can operate on the outgoing request and the incoming response.
Setting up Interceptors:-
To set up interceptor, we need a class which will be injectable class and implementing the HttpInterceptor. When we implement this Interface, then we have a method called intercept which has the body like below.
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {}
It has two parameters "req" and "next" which are HttpRequest and HttpHandler respectively.
src/app/auth/HeaderInterceptor.ts
----------------------------------
import { Injectable } from '@angular/core' 
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse } from '@angular/common/http'; 
import { Observable } from 'rxjs/Observable'; 
import 'rxjs/add/operator/do'; 
 
@Injectable() 
export class HeaderInterceptor implements HttpInterceptor { 
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { 
       
        const dummyrequest = req.clone({ 
            setHeaders: { 
                'AuthKey': '12345', 'DeviceID': '85645', 
                'content-type': 'application/json',
      'Authorization': 'Bearer My-token'
            } 
        }) 
        console.log("Cloned Request"); 
        console.log(dummyrequest); 
        return next.handle(dummyrequest); 
    } 


import { BrowserModule } from '@angular/platform-browser'; 
import { NgModule } from '@angular/core'; 
import { HttpClientModule,HTTP_INTERCEPTORS } from '@angular/common/http'; 
import {FormsModule} from '@angular/forms' 
import { AppComponent } from './app.component'; 
import {HeaderInterceptor} from './Interceptors/HeaderInterceptor' 
@NgModule({ 
  declarations: [ 
    AppComponent, 
    EmpoyeeHomeComponent 
  ], 
  imports: [ 
    BrowserModule,HttpClientModule,FormsModule 
  ], 
  providers: [EmployeeDataService, 
    { provide: HTTP_INTERCEPTORS, useClass: HeaderInterceptor, multi: true } 
   
  ], 
  bootstrap: [AppComponent] 
}) 
export class AppModule { }
Ref: https://www.c-sharpcorner.com/article/angular-5-http-client-interceptors/

Method:2
=========

ANGULAR 5 HTTPINTERCEPTOR – ADD BEARER TOKEN TO HTTPCLIENT REQUESTS
--------------------------------------------------------------------
In this article I will describe how to add a Http Authentication Bearer token to each request done from Angular via HttpClient by implementing a Angular 5 HttpInterceptor. This way the bearer token has not be added to each request separately while doing Ajax request e.g. to a REST api. This is for example useful, if you have some api that is protected by OAuth and you have to sent a JWT token in order to get access.
app.module.ts
---------------
import { HTTP_INTERCEPTORS } from '@angular/common/http';

@NgModule({

...
providers: [
...
{  provide: HTTP_INTERCEPTORS,
   useClass: CustomHttpInterceptor,
   multi: true
},
...
})

CustomHttpInterceptor.ts:
---------------------------
import { Location } from '@angular/common';
import { Injectable } from '@angular/core';
import { HttpInterceptor } from '@angular/common/http';
import { HttpRequest } from '@angular/common/http';
import { HttpHandler } from '@angular/common/http';
import { HttpEvent } from '@angular/common/http';
import { MsalService } from '../services/msal.service';
import { HttpHeaders } from '@angular/common/http';
import 'rxjs/add/observable/fromPromise';

@Injectable()
export class CustomHttpInterceptor implements HttpInterceptor {
  constructor(private msalService: MsalService) {}
 
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return Observable.fromPromise(this.handleAccess(request, next));
  }

  private async handleAccess(request: HttpRequest<any>, next: HttpHandler):
      Promise<HttpEvent<any>> {
    const token = await this.msalService.getAccessToken();
    let changedRequest = request;
    // HttpHeader object immutable - copy values
    const headerSettings: {[name: string]: string | string[]; } = {};

    for (const key of request.headers.keys()) {
      headerSettings[key] = request.headers.getAll(key);
    }
    if (token) {
      headerSettings['Authorization'] = 'Bearer ' + token;
    }
    headerSettings['Content-Type'] = 'application/json';
    const newHeader = new HttpHeaders(headerSettings);

    changedRequest = request.clone({
      headers: newHeader});
    return next.handle(changedRequest).toPromise();
  }

}
option:3
==========
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpHeaders  } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class BearerTokenInterceptor implements HttpInterceptor {
  constructor() {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    let currentToken = localStorage.getItem('AccessToken');   // get toeken from API i.e APP_INITIALIZER
    console.log(currentToken,'<---jwt token  Http Interceptors');
    if (currentToken && currentToken != null) {
      request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${currentToken}`
        }
      });
    }
    return next.handle(request);
  }
}

A couple of things to notice here. Since I’m working with async / await and I use Promises in my code and the intercept method returns an Observable, I have to convert my Promise to an Observable using the Observable.fromPromise method.

In the handleAccess method I get my access token from my msalService. This is a service for handling login / access etc. using Microsoft Authentication Library for JavaScript (In my case Azure AD B2C).

The next step is to actually add the token to the HttpClient request.

Immutable Request / RequestHeader
One very important point is, that you cannot simply set or add new headers to the request object.

The request and header objects are immutable. Even if you change something by adding a new header or trying to set some header, this will not work. This took me a while to figure out, because the api of these objects allows you to do so. But the changes you make are then not reflected in the requests you make later on

REf: https://www.illucit.com/en/angular/angular-5-httpinterceptor-add-bearer-token-to-httpclient-requests/

Ng5- APP_INITIALIZER - Run Code During App Initialization

Ng5- APP_INITIALIZER - Run Code During App Initialization
----------------------------------------------------------------------------
Before App Load excute promise for Base Url:
Method: 1
----------
import app-load as one module in app.module.ts instead iof provider with APP_INITIALIZER property
i.e
https://www.intertech.com/Blog/angular-4-tutorial-run-code-during-app-initialization/


add provider and base url Service inside app.module.ts Providers section, with APP_INITIALIZER

https://devblog.dymel.pl/2017/10/17/angular-preload/


app.module.ts
--------------
import { JokesProvider } from './JokesProvider';

export function jokesProviderFactory(provider: JokesProvider) {
  return () => provider.load();
}


 @NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpModule
  ],
  providers: [
    JokesProvider,
    { provide: APP_INITIALIZER, useFactory: jokesProviderFactory, deps: [JokesProvider], multi: true }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }


JokesProvider.service.ts
------------------------
@Injectable()
export class JokesProvider {

    private joke: JokeModel = null;

    constructor(private http: Http) {

    }

    public getJoke(): JokeModel {
        return this.joke;
    }


    //option :1  call Obserabletype of Promise direct service call
    load() {
        return new Promise((resolve, reject) => {
            this.http
                .get('https://api.icndb.com/jokes/random')
                .map(res => res.json())
                .subscribe(response => {
                    this.joke = response['value'];
                    resolve(true);
                })
        })
    }
// option:2 Call directly Prmoise/Observable to load - MAke eaen faster ( create seperate service file)
this.privateService.GetData().toPromise().then(
      (response:any) => {
//expected out put / result from API

}).catch((error) =>{
      console.log(error);


app.component.ts
-----------------
@Component({
  selector: 'app-root',
  template: `
  <h1>Joke of the day:</h1>
  <p>{{jokeModel.joke}}</p>`,
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'app';
  jokeModel: JokeModel;
 
  constructor(jokesProvider: JokesProvider) {
    this.jokeModel = jokesProvider.getJoke();
  }

  ngOnInit() {
    console.log("AppComponent: OnInit()");
  }
}

Ng5-Iframe in Angular 5componen

Ng5-Iframe in Angular 5component -

To load externa site inside Angular
================================
Angular untrust external site has to be inject inside Angualr App.
So, Sanitize and make trustable html5 iframe as truable.
Else Request mapping error  with cross script erro will throw.

method:1
--------
It will workin Chrome, firefox, IE
component.html
--------------
<iframe src="" frameborder="0" height="700" ></iframe>

component.ts
-------------
url = 'http://google.com';
    constructor(    private hostElement: ElementRef,  ) { }

ngOnInit(){
const iframe = this.hostElement.nativeElement.querySelector('iframe');
iframe.src = this.url;
}

method:2
---------
It contains, method 1 with full proper code implementation. And New soln.
template.html
--------------
<iframe src="" frameborder="0" height="700" ></iframe>
<iframe [src]="safeURL" frameborder="0" height="700" ></iframe>

component.ts
------------
import { Component, OnInit , Input, ElementRef} from '@angular/core';
import { DomSanitizer, SafeResourceUrl, SafeUrl , } from '@angular/platform-browser';

export component{
  url = 'http://google.com';
  safeURL : SafeResourceUrl;
 
    constructor(private sanitizer: DomSanitizer, private hostElement: ElementRef,) {  }
 
ngOnInit() {
    const iframe = this.hostElement.nativeElement.querySelector('iframe');   // work in chrome,FF,IE
    iframe.src = this.url;
    this.safeURL = this.sanitizer.bypassSecurityTrustResourceUrl( this.url );  //Not not workin IE
  }
}

Ref:
https://github.com/angular/angular/issues/16994  solution->juanbenitopr 

Ng6 - Upgrade from NG5- Ng6

Ng6 - Upgrade from NG5- Ng6
===========================

delete node_module folder in Exisitng NG_APP (angular 5)

Note: Node version .8.11. and above is required for NG6

NG_APP>

npm uninstall @angular/cli

npm cache verify

npm install @angular/cli@6

paste the package.json and angular.json file in DC -WEB

npm install

local run : ng serve

prod build in local ng build --prod