Tuesday 17 March 2020

NG8 - Model , Interface based API response in component and Service

NG8 - Model , Interface based API response in component and Service
=====================================================================

model-data.ts
==============
export interface ModelData{
 id: string;
 name: string;
 dept: string;
 salary: number;
 doj:any;
}

model-response.ts
==================

import { ModelData } from './model-data';

export interface {

 status: string;
 statusDetails: string;
 responseCount: number;
 data: ModelData[];
}


app.component.ts
=================
import { AppService } from './app.service';
import { ModelResponse } from './model-response';
import { ModelData } from './model-data';

@Component({
selector: 'app',
templateUrl:'./component.html',
styleUrls:['./component.less']

export class AppComponent implements OnInit, OnDestroy {

 resData : ModelData[];
 constructor( private appServiceDI: AppService){

 }
ngOnInit() {
// load data from API
this.appServiceDI.get_listData().subcribe( (res: ModelResponse)  =>{
if(res.status){
this.resData = res.data;
}
else{
this.resData = [];
},
(error) => {
this.resData = [];
console.log(error);
}
}
}
}

app.service.ts
================

import { ModelResponse } from './model-response';

@Injectable()

export class AppService{

 constructor( private http: HttpClient )

 get_listData():Observable(<any>){
    return this.http.get<ModelResponse>('apiUrl').map(
      res => {
        const data = res;
        return data;
      });
  }
 
}

app.component.html
====================

<h4> to display Employee details </h4>

<div *ngFor="let emp of resData"> 
  <div>
<span>{{ emp.id }}</span>   <span>{{ emp.name }}</span>
  </div>
</div>

NG8- Validation - upload header columns order in Angular

NG8- Validation - upload header columns order in Angular
========================================================
component.ts:
===================

fileReaded;
arrIndex;
onFileSelect(fileInput: any){
  //read file from input
  this.fileReaded = fileInput.target.files[0];
 
  let reader: FileReader = new FileReader();
  reader.readAsText(this.fileReaded);
 
    reader.onload = (e) => {
      let csv: any = reader.result;
      let headers;
      let allTextLines = csv.split(/\r|\n|\r/);
      //col_ord1|col_ord2|col_ord3|col_ord4|col_ord5|col_ord6

      let checkHeader = [ "col_ord1|col_ord2|col_ord3|col_ord4|col_ord5|col_ord6", "", ""]
      for (let i = 0; i < allTextLines.length; i++) {
        // split content based on comma
        let data = allTextLines[i].split(',');
        //console.log(data)
     
        var c= checkHeader.filter(checkHeader => !data.includes(checkHeader));

        if(c.length == 0){
          headers=allTextLines[i].split(',');
          this.arrIndex = i+1;
          console.log('header matchecd');
          break;
        }
        else{
          console.log('header doesnt matchec');
        }
      }


      let lines = [];
   
      for (let i = this.arrIndex; i < allTextLines.length; i++) {
        // split content based on comma
        let data = allTextLines[i].split(',');
        if (data.length === headers.length) {
          let tarr = [];
          for (let j = 0; j < headers.length; j++) {
            tarr.push(data[j]);
          }

          // log each row to see output
          console.log(tarr);
          lines.push(tarr);
    }
     
      }
      // all rows in the csv file
     // console.log(">>>>>>>>>>>>>>>>>", lines);
    }
 }


  template.html
  ==============
 
 
  <div class="form-group">
    <input type="file" (change)="onFileSelect($event)" name="myfile">
  </div>

NG7-Angular Drag and expand Div or and popup

NG7-Angular Drag and expand Div or and popup
-----------------------------------------------------------

npm install --save angular-resizable-element

custom.module.ts
---------------
import { ResizableModule } from 'angular-resizable-element';
@NgModule({
  declarations: [
    Component,
    ModalComponent
  ],
  imports: [
    CommonModule,
    ResizableModule]

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

/* tslint:disable:max-inline-declarations */
import { Component } from '@angular/core';
import { ResizeEvent } from '../src';

@Component({
  selector: 'mwl-demo',
  styles: [
    `
      .rectangle {
        position: relative;
        top: 200px;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 300px;
        height: 150px;
        background-color: #fd4140;
        border: solid 1px #121621;
        color: #121621;
        margin: auto;
      }
      .resize-handle-top,
      .resize-handle-bottom {
        position: absolute;
        height: 5px;
        cursor: row-resize;
        width: 100%;
      }
      .resize-handle-top {
        top: 0;
      }
      .resize-handle-bottom {
        bottom: 0;
      }
      .resize-handle-left,
      .resize-handle-right {
        position: absolute;
        height: 100%;
        cursor: col-resize;
        width: 5px;
      }
      .resize-handle-left {
        left: 0;
      }
      .resize-handle-right {
        right: 0;
      }
    `
  ],
  template: `
    <div class="text-center">
      <h1>Drag and pull the edges of the rectangle</h1>
      <div
        class="rectangle"
        [ngStyle]="style"
        mwlResizable
        [validateResize]="validate"
        [enableGhostResize]="true"
        [resizeSnapGrid]="{ left: 50, right: 50 }"
        (resizeEnd)="onResizeEnd($event)">

        <div class="resize-handle-top" mwlResizeHandle [resizeEdges]="{ top: true }"></div>
        <div class="resize-handle-left" mwlResizeHandle [resizeEdges]="{ left: true }"></div>
        <div class="resize-handle-right" mwlResizeHandle [resizeEdges]="{ right: true }"></div>
        <div class="resize-handle-bottom" mwlResizeHandle [resizeEdges]="{ bottom: true }"></div>
      </div>
    </div>
  `
})
export class DemoComponent {
  public style: object = {};

  validate(event: ResizeEvent): boolean {
    const MIN_DIMENSIONS_PX: number = 50;
    if (
      event.rectangle.width &&
      event.rectangle.height &&
      (event.rectangle.width < MIN_DIMENSIONS_PX ||
        event.rectangle.height < MIN_DIMENSIONS_PX)
    ) {
      return false;
    }
    return true;
  }

  onResizeEnd(event: ResizeEvent): void {
    this.style = {
      position: 'fixed',
      left: `${event.rectangle.left}px`,
      top: `${event.rectangle.top}px`,
      width: `${event.rectangle.width}px`,
      height: `${event.rectangle.height}px`
    };
  }
}

Ref:
https://github.com/mattlewis92/angular-resizable-element/blob/master/demo/demo.component.ts
https://mattlewis92.github.io/angular-resizable-element/docs/#development

Monday 16 March 2020

NG7 - How to unit test the angular application particular component or module

NG7 - How to unit test the angular application particular component or module :
-------------------------------------------------------------------------------

soln:1 - Ref:1
Ref: https://dzone.com/articles/running-karma-test-case-for-single-spec-file

Soln1: ref:2- shorthand
Step 1:
-------

Configure test.ts file inside src folder:

const context = require.context('./', true, /\.spec\.ts$/);
Replace /\.spec\.ts$/ with the file name you want to test. For example: /app.component\.spec\.ts$/

This will run test only for app.component.spec.ts.

Step 2
--------
Run ng test --code-coverage

Now Karma and Jasmine will check only Test-Demo.Spec.ts.

Before you push, you should run all the test cases and don’t push this file to the next repository.

Hope you enjoy.



Step 1.:- Module testing
--------
Run Karma on module base

const context = require.context('app/module-name/', true, /\.spec\.ts$/);
Replace require.context('./', true, with the module name you want to test. For example: 'custome-Module/', require.context(true)

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...