Wednesday, 28 March 2018

Ng4-ViewChild - Show ratio button based on condition using ViewChild

Ng4-ViewChild - Show ratio button based on condition using ViewChild
=======================================================

<input id="EXCEL" name="EXCEL" value="EXCEL" type="radio" #radioCheckedExcel/>

import { Component, Output,OnInit,Input, EventEmitter, ViewChild, ElementRef } from '@angular/core';

export class NewReportsComponent implements OnInit {

  @ViewChild('radioCheckedExcel') private radioCheckedExcel: ElementRef;
 
 
  EventTriggerFunciton(){
  this.radioCheckedExcel.nativeElement.checked = true;
  }
 
  ResetRatioButton(){
  this.radioCheckedExcel.nativeElement.checked = false;
  }

NG5-PostApplicaotinJSONToformData

NG5-PostApplicaotinJSONToformData
----------------------------------------------

Send the post data as Form data based
i.e => key1=val1&key2=val2..... from Object(json type)
Application type to form data type


component.ts
--------------
let data = {
    "key1":"val1",
    "key2":val2",
    "key3":"val3"
}
let PostObj = this.toParams(data)
  this._MyService.CreatePost(PostObj).subscribe( (data:any) => {
    try{
    }
    catch(e){
    }
});
           
 toParams(evtObj) {
    var p = [];
    for (var key in evtObj) {
        p.push(key + '=' + encodeURIComponent(evtObj[key]));
    }
    return p.join('&');
}



NG5- InMemoryWebApiModule - local DB

ng5- InMemoryWebApiModule
-------------------------------------

app.module.ts
-----------------

import { HttpClientInMemoryWebApiModule } from 'angular-in-memory-web-api';
import { InMemoryDataService }  from './in-memory-data.service';

@NgModule({
  imports: [
  ....
  .....
 
    // The HttpClientInMemoryWebApiModule module intercepts HTTP requests
    // and returns simulated server responses.
    // Remove it when a real server is ready to receive requests.
    HttpClientInMemoryWebApiModule.forRoot(
      InMemoryDataService, { dataEncapsulation: false }
    )
  ],
  declarations: [
  AppComponent
  ],providers: [ HeroService, MessageService ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

in-memory-data.service.ts
---------------------------
import { InMemoryDbService } from 'angular-in-memory-web-api';

export class InMemoryDataService implements InMemoryDbService {
  createDb() {
    const heroes = [
      { id: 11, name: 'Mr. Nice' },
      { id: 12, name: 'Narco' }
      ]
     return {heroes};
  }
}
mock-heroes.ts
---------------

import { Hero } from './hero';

export const HEROES: Hero[] = [
  { id: 11, name: 'Mr. Nice' },
  { id: 12, name: 'Narco' } 
];

hero.ts
--------
export class Hero {
  id: number;
  name: string;
}


hero.service.ts
----------------
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { catchError, map, tap } from 'rxjs/operators';

import { Hero } from './hero';
const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable()
export class HeroService {
  private heroesUrl = 'api/heroes';  // URL to web api

  constructor(
    private http: HttpClient,
    private messageService: MessageService) { }

  /** GET heroes from the server */
  getHeroes (): Observable<Hero[]> {
    return this.http.get<Hero[]>(this.heroesUrl)
      .pipe(
        tap(heroes => this.log(`fetched heroes`)),
        catchError(this.handleError('getHeroes', []))
      );
  }
 
 
dashboard.component.ts
----------------------
import { Hero } from '../hero';
import { HeroService } from '../hero.service';
export class DashboardComponent implements OnInit {
  heroes: Hero[] = [];

  constructor(private heroService: HeroService) { }

  ngOnInit() {
    this.getHeroes();
  }

  getHeroes(): void {
    this.heroService.getHeroes()
      .subscribe(heroes => this.heroes = heroes.slice(1, 5));
  }
 }

dashboar.template.ts
---------------------
 <a *ngFor="let hero of heroes" class="col-1-4"
      routerLink="/detail/{{hero.id}}">
    <div class="module hero">
      <h4>{{hero.name}}</h4>
    </div>
  </a>

Sunday, 4 March 2018

NG4- ngIf, else, ngIf then,else using ng-tempalte

NG4- ngIf, else, ngIf then,else using ng-tempalte
-------------------------------------------------------------
//our root app component
import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'else-cmp',
  template: `
    <button (click)="isValid = !isValid">update</button>
 
    <div *ngIf="isValid;else other_content">
       content here ...
    </div>

    <ng-template #other_content>other content here...</ng-template>

  `,
})
export class ElseComponent {
  isValid:boolean = true;
  constructor() {
  }
 
}



@Component({
  selector: 'else-then-cmp',
  template: `
      <button (click)="isValid = !isValid">update</button>

       <div *ngIf="isValid;then content else other_content"></div>
     
       <ng-template #content>content here...</ng-template>
       <ng-template #other_content>other content here...</ng-template>

  `,
})
export class ElseThenComponent {
  isValid:boolean = true;
  constructor() {
  }
 
}




@Component({
  selector: 'my-app',
  template: `
    <h4>Using else :</h4>
    <br>
    <else-cmp></else-cmp>
    <br>
    <br>
    <h4>Using else then:</h4>
    <br>
    <else-then-cmp></else-then-cmp>
  `,
})
export class App {
  isValid:boolean = true;
  constructor() {
  }
 
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App , ElseComponent,ElseThenComponent],
  bootstrap: [ App ]
})
export class AppModule {}

Ref: https://plnkr.co/edit/XD5vLvmwTApcaHJ66Is1?p=preview

Wednesday, 21 February 2018

ES6 - Array intersection, Difference, symmetric => using Arrow Function

ES6 - Array intersection, Difference, symmetric =>
-----------------------------------------------------------------
There is a better way using ES6:
Intersection
============
 let intersection = arr1.filter(x => arr2.includes(x));
 For [1,2,3] [2,3] it will yield [2,3]. On the other hand, for [1,2,3] [2,3,5] will return the same thing.

Difference
==========
let difference = arr1.filter(x => !arr2.includes(x));
For [1,2,3] [2,3] it will yield [1]. On the other hand, for [1,2,3] [2,3,5] will return the same thing.

symmetric difference
====================
let difference = arr1.filter(x => !arr2.includes(x)).concat(arr2.filter(x => !arr1.includes(x)));

Ref: https://stackoverflow.com/questions/1187518/how-to-get-the-difference-between-two-arrays-in-javascript

Saturday, 17 February 2018

NG5- Event Bubling

NG5- Event Bubling
-------------------------
DOM events provide a mechanism that can prevent bubbling. It is the stopPropagation method. 
@Component({
  selector: 'event-bubbling',
  template: `
    <div>
      <button (click)="onClick($event, 'Button 1')">Button 1</button>
      <button (click)="onClick($event, 'Button 2')">Button 2</button>
    </div>
  `
})
export class EventBubblingComponent {
  @Output() click = new EventEmitter();

  onClick(event: Event, button: string) {
    event.stopPropagation();

    this.click.next(button);
  }
}

E.g
----
<div (click)="hidetheDiv()"> <span (click)="maketheFunctionCall($event,item)"> API Call </span>  Close X</div>

  
  maketheFunctionCall(event:Event,item){
    event.stopPropagation();
    console.log("Make the API call", item)
  }
  
  hidetheDiv(){
  this.Div = false;
  }

Thursday, 1 February 2018

NG5- Module - App.module.ts

NG5- Module - App.module.ts
========================

=>Angular apps are modular and Angular has its own modularity system called NgModules. NgModules are a big deal.

=>Every Angular app has at least one NgModule class, the root module, conventionally named AppModule.
=>While the root module may be the only module in a small application, most apps have many more feature modules, each a cohesive block of code dedicated to an application domain, a workflow, or a closely related set of capabilities.

->An NgModule, whether a root or feature, is a class with an @NgModule decorato
NgModule is a decorator function that takes a single metadata object whose properties describe the module. The most important properties are:

->declarations - the view classes that belong to this module. Angular has three kinds of view classes: components, directives, and pipes.

->exports - the subset of declarations that should be visible and usable in the component templates of other modules.

->imports - other modules whose exported classes are needed by component templates declared in this module.

->providers - creators of services that this module contributes to the global collection of services; they become accessible in all parts of the app.

->bootstrap - the main application view, called the root component, that hosts all other app views. Only the root module should set this bootstrap property

generic.app.module.ts
---------------------

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
@NgModule({
  imports:      [ BrowserModule ],
  providers:    [ Logger ],
  declarations: [ AppComponent ],
  exports:      [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }


Sample Ng-cli app.module at initial level
--------------------------------------------

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
// import { routing } from './app.routing.ts';  =>  App routing file needs to include 
import { AppComponent } from './app.component';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [ // import Angular's modules ->BrowserModule,    HttpModule,    RouterModule,    FormsModule,    ReactiveFormsModule, <= coresponding import statement as to add 
BrowserModule   
  ],
  providers: [],   // expose our Services and Providers into Angular's dependency injection  Mostly service files <= coresponding import statement as to add 
  bootstrap: [AppComponent]
})
export class AppModule { }

NG5- angular-cli change port to 3000 in angular-cli.json

NG5- angular-cli change port to 3000 in angular-cli.json or ng serve --port 3000 cmd
==========================================================

soln:1
--------

Edit with Angular-CLI 1.0.0

You can now directly define the used port in the .angular-cli.json file by defining the property like this:

{
    "defaults": {
"styleExt": "scss",
"component": {},
        "serve": {
            "port": 3000
        }
    }
}
Here is a direct link to all available options for the configuration: Angular-CLI options configuration

Soln:2
-------
Old Answer

You can configure it directly in your packages.json, change your start scripts by:

"start": "ng serve --port 2500",
And then run your server with npm start


this will override the .angular.cli.json file. app will run in 2500 port.


Soln:3
------
You can also try with this to run your application in visual studio code -:

ng serve --open --port 4201

you can give any port number. 

*** It will in open in default browser. e.g I.E edge in windows or your preferred browser.

Ref: https://stackoverflow.com/questions/41260194/angular-cli-change-port-to-3000-in-angular-cli-json

Wednesday, 31 January 2018

NG4-router - 2 way to implement. 1.routing within module file, 2. routing file as separate

NG4-router  - 2 way to implement. 1.routing within module file, 2. routing file as separate
===========

router we can achieve based on url change.

Method:1
--------
Write the routing in Module file it self. No need to import or create mycompoent.routing.ts file externally.
Most important = We can achieve Lazy loading using ForChild(routes)

app.module.ts
-------------
import { NgModule, ApplicationRef } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { Component1Module } from './modules/my-Componet1/Componet1.module';
import { service } from './modules/Serivice';


@NgModule({
  bootstrap: [App],
  declarations: [   App, RedirectPage   ],
 
  imports: [ // import Angular's modules
    BrowserModule,
    HttpModule,
    RouterModule,
    MyComponet1Module
],
  providers: [ // expose our Services and Providers into Angular's dependency injection
Service,
  ]
})

export class AppModule {

  constructor() {
  }
}


app.component.html
------------------

<main >
 <nav>
  <a routerLink='/first-component' >HTML</a> |
  <a routerLink='/Second-Component' >CSS</a> |
  </nav>
  <router-outlet></router-outlet>
</main>


Component1.module.ts
--------------------


const routes: Routes = [
  {
    path: 'first-component',
    component: Component1.component
  }
]
const routing = RouterModule.forChild(routes);

@NgModule({
  imports: [],
  declarations: [Component1Component],
   providers: []
   })

export class component1Module { }

Component1.Component.ts
-----------------------
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'compare',
  templateUrl: './Component1.html',
  styleUrls: ['./Component1.scss']
})
export class Component1Component implements OnInit {

  constructor() { }

  ngOnInit() {
  }
 }


Component1.html
---------------
component1 Content comes Here...



Method:2
--------
create a Routing file for every separate module and do the routing wiht routes { path: '/compnent2, component:}
How to include multiple component into major component and display - dashboard (aggr and charts )

Same the app.module.ts , app.component.ts and app.compnent.html


Component2.module.ts
--------------------
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { routing } from './my-reports.routing';

@NgModule({
  imports: [ routing ],     // here we import routing from external routing file.
  declarations: [Component2Component],
  providers: []
   })

export class component2Module { }

Component2.routing.ts
----------------------
import { Routes, RouterModule } from '@angular/router';
import { ModuleWithProviders } from '@angular/core';
import { MyReportsComponent } from './my-reports.component';

const routes: Routes = [
  {
    path: 'Second-Component',
    component: MyReportsComponent
  }
]

export const routing: ModuleWithProviders = RouterModule.forChild(routes);


Component2.Component.ts
-----------------------
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'compare2',
  templateUrl: './Component2.html',
  styleUrls: ['./Component2.scss']
})
export class Component2Component implements OnInit {

  constructor() { }

  ngOnInit() {
  }
 }


Component2.html
---------------
component2 Content comes Here...


Tuesday, 30 January 2018

Ng4- Apply Css ngClass (attribute directive) based on more than one condition( && ||)

Ng4- Apply Css ngClass (attribute directive) based on more than one condition( && ||)
===========================================================
Use case:1
----------
you can't directly use <div [ngClass]="{'cssClass1': value1 && value2,'cssClass2': value1 || value2 }"} Css effect in Template </div>
firefox browser doesn't support the && perfectly.
Use case:
----------
more than 2 condition check in with css ngClass make performance better via component function
<div [ngClass]="{'cssClass1': value1,'cssClass2': value2, 'cssClass3':value3}"} Css effect in Template </div>

Solution:
----------
Component.template.html
------------------------
<div [ngClass]="{'cssClass1': isCondtionTrue(),'cssClass2': isvalid() }"} Css effect in Template </div>

Component.component.ts
----------------------
import { component } from '@angular/component';
import { } from '@angular/route';

@Component({
  selector: 'ngClassFunction',
  templateUrl: './Component.template.html',
  styleUrls: ['./Component.template.scss'],
  encapsulation: ViewEncapsulation.None
})
export class ComponentComponent implements OnInit, OnChanges {

constructor(){
}
isCondtionTrue(){
if(this.value1 && this.value2)
return true;
else false;
}
isvalid(){
if(this.value1 && this.value2)
return true;
else false;
}

}

NG4- AOT Build failed due to Javascript Heap Out of Memory

NG4- AOT Build failed due to Javascript Heap Out of Memory 
=============================================

It will occur build memory space is less to build our Angular 2 code.
Here we are forcing to increase memory space to build.

Many thanks! Working perfectly with
node --max_old_space_size=8192 node_modules/@angular/cli/bin/ng serve --aot
Or for build
node --max_old_space_size=8192 node_modules/@angular/cli/bin/ng build -prod


Ref: https://github.com/angular/angular/issues/20687

Redux vs Redux Toolkit vs React Context

  These are often confused. Feature Redux Redux Toolkit Context API Purpose State management Simplifies Redux Shares values in Rea...