Sunday 19 April 2020

MicroFrontend - UI Angular9 custom element with Web components

MicroFrontend - UI Angular custom element with Web components:
------------------------------------------------------------------------
NodeJs 10.x Ng-CLI 9.0.1 as on 19-apr-2020 12:21AM

Source CODE: https://github.com/gnganpath/Angular9-MicroFrontend-customElement-WebComponent

MicroApp:

Step:1
ng new MicroApp

complete the All the development of Child/Micro app as entire app or particular component as ??? Particular module???
Note: For Module ill be part of any component. So, The idea will module will become component as mciroApp

Step:2
MicroApp:> ng add @angular/elements

will generate / Impact
package.json ->
  "@angular/elements": "^9.0.7",
  "document-register-element": "1.8.1",   --> change the version 1.8.1 if not then npm install

polyfill.ts ->Automatically Import this packages into polyfills.ts file: if not do it maually and npm i
  import 'document-register-element';

Step:3

Install some polyfills:
MicroApp:> npm i @webcomponents/custom-elements --save

Import those packages into polyfills.ts file:

import "@webcomponents/custom-elements/src/native-shim";
import "@webcomponents/custom-elements/custom-elements.min";

Step:4
MicroApp:> ng add ngx-build-plus

will generate / Impact
package.json ->
 "ngx-build-plus": "^9.0.6",


"architect": {  "build": {    "builder": "ngx-build-plus:browser  .... $while building$ "builder": "ngx-build-plus:build",  ....
"budget": [
              // to avoid budget Error  Delete this part in Micro UI angular.json , ->budget error occurs
                {
                   "type": "anyComponentStyle",
                   "maximumWarning": "2mb",  //from 6kb
                    "maximumError": "5mb"     // from10kb
                }
              ]
"serve": {    "builder": "ngx-build-plus:dev-server",    ...
"test": {    "builder": "ngx-build-plus:karma",


Step:5
MicroApp:> app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, Injector} from '@angular/core';

import { createCustomElement } from '@angular/elements';

bootstrap: [],   // while develop it will get fill , but in build time it must be empty
entryComponents: [AppComponent]   // entire app as microUI

export class AppModule {

  constructor(private injector: Injector){   }

  ngDoBootstrap(){
    const myCustomElement = createCustomElement(AppComponent, { injector: this.injector });
    customElements.define('micro-app1', myCustomElement);    /// micto-app is <custom-elment-tag> like <header> <footer>
  }
}

Step:6

build the child app and generate dist for master/parent app

MicroApp:>ng build --prod --output-hashing none --single-bundle true --bundle-styles false
Notes:
--output-hashing none ->will avoid hashing the file names.
--single-bundle true ->will bundle all the compiled files into a single JS file.
--bundle-styles false ->if we follow the same library css for all the projects

Step:6.1
Sometimes budget error will occur. so, Make the correction at MicroApp angular.json
 "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "2mb",  //from 6kb
                  "maximumError": "5mb"     // from10kb
                }
              ]
copy the dist folder into master app src/app/assets/MicroApp --> which contains Main.js, index.html,3 other files

Step:6.2

To do the auto copy -> npm install copyfiles -g   // in the machine/ laptop

MciroApp:> npm run copfiles : copyfiles ./dist/*.* MasterAppPath/src/app/assets

ALternatively :   ng build make output path from MciroApp

Step:7

To generate mutliple micro app follow the step -> Step 1- 6

Another child app or MciroApp dist


Step:8 
MasterApp / ContainerApp /
ng new MasterApp

Step: 9 ( Repeat Step 2 )
MasterApp:> ng add @angular/elements

will generate / Impact
package.json ->
  "@angular/elements": "^9.0.7",
  "document-register-element": "1.8.1",   --> change the version 1.8.1 if not then npm install

polyfill.ts ->Automatically Import this packages into polyfills.ts file: if not do it manually and npm i
  import 'document-register-element';

Step:10 (  Repeat Step 3 )  [ No need ngx-build - Which is step 4 ]

Install some polyfills:
MicroApp:> npm i @webcomponents/custom-elements --save

Import those packages into polyfills.ts file:

import "@webcomponents/custom-elements/src/native-shim";
import "@webcomponents/custom-elements/custom-elements.min";

Step:11

MasterApp
app.module.ts
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

bootstrap: [AppComponent],
  schemas: [CUSTOM_ELEMENTS_SCHEMA]  // which allows custom element as recognized element in master App
})
export class AppModule { }

Step:12
MastetApp:

Whichever the component need to import/use the in that component

MasterApp - Requiedcomponent.component.ts

  childAppPath = 'http://localhost:4200/assets/MicroApp/main.js';
  constructor(){   }

  ngOnInit() {
    this.loadScript(this.childAppPath); 
  }

  loadScript(scriptPath): void {

    var alreadyLoaded = false;

    for (var scriptIndex in document.scripts) {
     // console.log(scriptPath, scriptIndex, document.scripts[scriptIndex].src)
      if (!alreadyLoaded && scriptPath === document.scripts[scriptIndex].src) {
        alreadyLoaded = true;
        break;
      }
    }
    if (!alreadyLoaded) {
      const content = document.getElementById('content');
      const script = document.createElement('script');
      script.src = scriptPath;
      content.appendChild(script);
    }
  }

Step:13
MasterApp -

<div id="content"><micro-app1></micro-app1></div>    // <micro-app1> is the custom Tag element mentioned at MicroApp app.module.ts

MasterApp:> ng serve ==> http://localhost:4200 default if chagne the default port Change the ChilAppPath/port

note: Some times, node js 12 will gives Build for http-server error. Other type of method .So maintain node js version 10 for angualr cli9
      Sometime Buget[.] will come, So increase the angular.json  in child app,


Ref: https://dzone.com/articles/build-micro-front-ends-using-angular-elements-the
Ref: https://www.techiediaries.com/angular/angular-9-web-components-custom-elements-shadow-dom
Ref: https://medium.com/@IMM9O/web-components-with-angular-d0205c9db08f

Thursday 16 April 2020

Ng9 Method to Micro UI angular Element

add into package.json files
----------------------------

 "@angular/elements": "^7.2.14",   "@angular/elements": "^8.2.13",

 "document-register-element": "1.8.1",
 "@webcomponents/custom-elements": "^1.1.3",
 "@webcomponents/webcomponentsjs": "^2.0.4"

 "ngx-build-plus": "^9.0.0",

webpcak.externals.js add the file into train booking root level
----------------------------------------------------------------
module.exports = {
externals: {
},
output: {
jsonpFunction: 'webpackJsonpAppname',
library: 'assetreview'
}
};


app.component.ts:
---------------------

import {createCustomElement} from "@angular/elements";

 bootstrap: [],
 entryComponents: [AppComponent] 

 export class AppModule {
 constructor(private injector: Injector) { }

  ngDoBootstrap() {
    const myCustomElement = createCustomElement(AppComponent, { injector: this.injector });
    customElements.define('micro-app1', myCustomElement);
  }

"build-angular-element": "ng build --prod --extraWebpackConfig webpack.externals.js --output-hashing none --single-bundle true --bundle-styles false"

Schema validation failed with the following errors:
  Data path ".budgets[1].type" should be equal to one of the allowed values.

 
   {
                  "type": "anyComponentStyle",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                }




polyfill.ts

// Used for browsers with partially native support of Custom Elements -
import '@webcomponents/custom-elements/src/native-shim';
import '@webcomponents/custom-elements/custom-elements.min';
import '@webcomponents/webcomponentsjs/custom-elements-es5-adapter.js'; 



    this.assetReviewPath = 'http://localhost:4200/assets/assetreview/main.js'
  this.loadScript(this.assetReviewPath, "asset-review");
  loadScript(scriptPath: string, tagName: string): void {

    var alreadyLoaded = false;

    for (var scriptIndex in document.scripts) {
      if (!alreadyLoaded && scriptPath === document.scripts[scriptIndex].src) {
        alreadyLoaded = true;
        break;
      }
    }
    if (!alreadyLoaded) {
      const content = document.getElementById('content');
      const script = document.createElement('script');
      script.src = scriptPath;
      content.appendChild(script);
    }

    this.currentApp = tagName;
  }
 
 
 
  flightAppPath = 'http://localhost:4500/assets/flight-booking/main.js';
  traintAppPath = 'http://localhost:4500/assets/train-booking/main.js';
  constructor(){


  }

  ngOnInit() {
    this.loadScript(this.flightAppPath);
    this.loadScript(this.traintAppPath);
  }

  loadScript(scriptPath): void {

    var alreadyLoaded = false;

    for (var scriptIndex in document.scripts) {
      if (!alreadyLoaded && scriptPath === document.scripts[scriptIndex].src) {
        alreadyLoaded = true;
        break;
      }
    }
    if (!alreadyLoaded) {
      const content = document.getElementById('content');
      const script = document.createElement('script');
      script.src = scriptPath;
      content.appendChild(script);
    }

  }

Angular 9 - Build Micro Front-Ends Using Angular Elements: The Beginner's Guide

Ng9 - Build Micro Front-Ends Using Angular Elements: The Beginner's Guide
----------------------------------------------------------------------------------------------
As of 16/apr/2020 node js 10.x and angualr cli9.X is working

https://github.com/gnganpath/angular-micro-frontend Source CODE

IDEA: "travel-booking" is master app ( container app)
which contains "flight-booking" and "train-booking" micro angular apps


Start with micro apps
Step:1
ng new flight-booking

Step:2
flight-booking:>ng add @angular/elements

Step:3
flight-booking:>ng add ngx-build-plus

Step:4
flight-booking:->package.json:
 document-register-element module to 1.8.1  // update from 1.7.2

Step:5 
flight-booking:> npm i -g http-server --save

Step:6
particular component from this angular micro app. Otherwise we can use entire app (appcomponent) itself will be micro app
flight-booking:> ng g c booking

 booking.html

<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
  <a href="javascript:alert('Welcome to Flight Booking App!!');" style="font-size:25px;">{{ title }}</a>
</div>

component.ts
 title = 'Flight Booking App from booking component';

Step:7 **** 
flight-booking::: app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, Injector } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { createCustomElement } from '@angular/elements';
import { BookingComponent } from './booking/booking.component';
@NgModule({
  declarations: [
    AppComponent,
    BookingComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [],  /// most important it must be empty after complete the local development. and run into micro app
  entryComponents: [
    BookingComponent
  ]
})
export class AppModule {
  constructor(private injector: Injector) {
  }
  ngDoBootstrap() {
    const myCustomElement = createCustomElement(BookingComponent, { injector: this.injector });
    customElements.define('app-flight-booking', myCustomElement);
  }
}

Step: 8 
flight-booking::: angular.json

after micro complete angula.json or run every time micro app build
"architect": {  "build": {    "builder": "ngx-build-plus:build",  ....    from Browser
"serve": {    "builder": "ngx-build-plus:dev-server",    ...
 "test": {    "builder": "ngx-build-plus:karma",

Step: 9
flight-booking:> ng build --prod --output-hashing none --single-bundle true

Step:10 
flight-booking:>http-server ./dist/flight-booking -p 8081

Similarly, create another custom element, train-booking, and run the server with port 8082.

Step: 11 Repeat step 1-10
Follow the step 1-10for second micro app which is train-booking with or without routing(entire app)
http-server ./dist/train-booking -p 8082

Step:12
ng new travel-booking

Step:13
travel-booking:::
index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>TravelBooking</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
  <div style="margin-bottom: 10px;" id="flight-booking-container"><app-flight-booking></app-flight-booking></div>
  <div id="train-booking-container"><app-train-booking></app-train-booking></div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/zone.js/0.9.1/zone.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/2.2.10/custom-elements-es5-adapter.js"></script>
  <script type="text/javascript" src="http://localhost:8081/main.js"></script>
  <script type="text/javascript" src="http://localhost:8082/main.js"></script>
</body>
</html>

we can include <app-flight-booking></app-flight-booking> any where inside src/app
app-flight-booking is  custom Elment defined from every micro app app.module using createcustomElement


Step: 14 
travel-booking::angular.json
"serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "travel-booking:build",
            "port": 8080
          }

Ref:https://dzone.com/articles/build-micro-front-ends-using-angular-elements-the

  
  mutli framework angualr, react, vue, ember micro front-end
https://medium.com/javascript-in-plain-english/create-micro-frontends-using-web-components-with-support-for-angular-and-react-2d6db18f557a

Tuesday 14 April 2020

Ng9-Ag-Grid - Infinite scroll

Ng9-Ag-Grid - Infinite scroll
==============================

App.module.ts
----------------
import { AgGridModule } from 'ag-grid-angular';
import { AppComponent } from './app.component';

@NgModule({
  imports:      [ BrowserModule, FormsModule, AgGridModule.withComponents([]) ],
 
 
app.component.html
--------------------

<div style="flex-grow:1; height: 1px;">
    <ag-grid-angular style="width: 100%; height: 100%" class="ag-theme-balham"
                      [gridOptions]="gridOptions"
                      [columnDefs]="columnDefs"
                      (gridReady)="onGridReady($event)"
                      #grid>
    </ag-grid-angular>
  </div>
</div> 

app.component.ts
-----------------
import { Component, HostListener, Input, ViewChild } from '@angular/core';
import { GridOptions, IDatasource, IGetRowsParams, ColDef } from 'ag-grid';
import { AgGridNg2 } from 'ag-grid-angular';
import { Observable } from 'rxjs';
import 'rxjs/add/observable/of';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  public columnDefs: any[];
  public rowData: any[];
  public gridOptions: any;
  public info: string;
  @ViewChild('grid') grid: AgGridNg2;

  constructor() {
    this.columnDefs = [
      { headerName: 'One', field: 'one' },
      { headerName: 'Two', field: 'two' },
      { headerName: 'Three', field: 'three' }
    ];

    this.gridOptions = {
      rowSelection: 'single',
      cacheBlockSize: 100,
      maxBlocksInCache: 2,
      enableServerSideFilter: false,
      enableServerSideSorting: false,
      rowModelType: 'infinite',
      pagination: true,
      paginationAutoPageSize: true
    };
  }

    private getRowData(startRow: number, endRow: number): Observable<any[]> {
      // This is acting as a service call that will return just the
      // data range that you're asking for.
      var rowdata = [];
      for (var i = startRow; i <= endRow; i++) {
        rowdata.push({ one: "hello", two: "world", three: "Item " + i });
      }
      return Observable.of(rowdata);
    }

    onGridReady(params: any) {
      console.log("onGridReady");
      var datasource = {
        getRows: (params: IGetRowsParams) => {
          this.info = "Getting datasource rows, start: " + params.startRow + ", end: " + params.endRow;       
          this.getRowData(params.startRow, params.endRow)
                    .subscribe(data => params.successCallback(data));         
        }
      };
      params.api.setDatasource(datasource);

    }
}


Ref: https://stackblitz.com/edit/ag-grid-infinite-scroll-example?file=src%2Fapp%2Fapp.component.ts

ag-grid getting start - angular::
https://www.ag-grid.com/angular-grid/



https://stackblitz.com/angular/yjpvxqbpmgkb?file=src%2Fapp%2Fapp.component.spec.ts

React + Typescript_ Module federation _ Micro Front end -Standalone and integrated

Module Federation The Module Federation is actually part of Webpack config. This config enables us to expose or receive different parts of t...