Tuesday, 10 April 2018

Ng5- Diff type of routerLink implmentation

Diff type of routerLink implmentation
============================
<nav>
    <a routerLink='/home'></a>
    <a routerLink='/about'></a>
</nav>

case:1
-----
<div *ngFor="let user of userList" [routerLink]="['detail', uer.name]"> {{ user.name }} </div>

case:2
-----
(click)="showUserDetails(user)"

Incase we do the navigation from component function means
 showUserDetails(user){
    this.router.navigate(['user', user.login]);
  }


to make the router navgation implement  routerLink='/home'
If you use parameter passing in router link [routerLink]="['detail', uer.name]"

Sunday, 8 April 2018

Angular5 - POC - routing - route params, RxJs Observable with service, tamplate binding, Event binding, Material desing impl

Angular5 POC
============
RxJs Observable with service
tamplate binding, Event binding,
Material desing imple
routing - route params
github link : https://github.com/gnganpath/Angular-6videos-thatJsdude

video:1 -> Installation and requirement software - Local dev environment
----------
Download node js , download and install VS code follow the agular cli version
npm install -g @angular/cli
ng new PROJECT-NAME
cd PROJECT-NAME
ng serve      -> no need of npm install is required here.
ng serve --host 0.0.0.0 --port 4201


video:2 -> component, tempalte binding, Event Handler
----------
bangularbangk$ ng g c circular

inside app.hml - template binding
bind the circular template using <app-circular>

app-circular.html
(click)="changeTextEventHandler()"

app.component.ts
public changeTxt = "initial text";

ngOnInit(){
this.changeTxt = "update text in OnInt";
}

changeTextEventHandler(){
this.changeTxt = "Event handler in child component";
}

video:3 -> Service, Observable, RxJS
----------

bangularbangk$ ng g service github/github

RxJs/Observale ->
app.module.ts
import { HttpClientModule } from '@angular/common/http';
...
imports: [
    BrowserModule,
    HttpClientModule
  ],

github.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map'
@Injectable()
export class GithubService {
  constructor(private http: HttpClient) { }
  getUser(searchText): Observable<any>{             // rxjs - observable call for API
    const url= 'http://api.github.com/search/users?q='+searchText;
    return  this.http.get(url).map(
      res => {
        const data = res;
        console.log(data)
        return data;
      }
    )
  }
}

search.html
<input type="text" (keyup)="onKeyup($event)">
<button (click)="getUsers()">Search</button>
<p>{{ searchCount }}</p>
<ol *ngIf="searchResult">
  <li *ngFor="let user of searchResult.items">{{ user.login }}</li>
</ol>

search.component.ts
import { Component, OnInit } from '@angular/core';
import {GithubService} from '../github/github.service';
 searchText;
  searchResult;
  searchCount;
  ....
  ....
  constructor(private githubService:GithubService) { }
   onKeyup(event){
    this.searchText = event.target.value;
  }
  getUsers(){
    console.log(this.searchText)
    this.githubService.getUser(this.searchText).subscribe(
      res =>{
       // console.log(res)
       this.searchResult = res;
       this.searchCount = res.total_count;
      }
    )};

Video:4 -> Angular2 Material Design

bangularbangk$ npm install --save @angular/material @angular/cdk

app.module.ts
import { MatCardModule } from '@angular/material/card';
....
 imports: [
    BrowserModule,
    HttpClientModule,
    MatCardModule
  ],
 
 
search.html
<div *ngIf="searchResult">
<mat-card class="example-card"  *ngFor="let user of searchResult.items">
  <mat-card-header>
    {{ user.login }}   
  </mat-card-header>
  <img class="profile-image" mat-card-image [src]="user.avatar_url" alt="Photo of a Shiba Inu">
  <mat-card-content>
    content
  </mat-card-content>
</mat-card>
</div>


Video:5 -> Routing, multiple routing, pass a route parameter, load data based on routing
--------

contnents
------------
<base href>
Router imports
Configuration
Router outlet
Router link
Router state
Summary

need to use base-href
index.html
<base href="/">

create appRoutes.ts

import { Routes } from '@angular/router';
import { CircularComponent } from './circular/circular.component';
import { SearchComponent } from './search/search.component';

export const appRoutes: Routes = [
    { path:'circular', component:CircularComponent },
    { path:'search', component:SearchComponent}
]

routeParams implementation in appRoutes.ts

import { Routes } from '@angular/router';
import { CircularComponent } from './circular/circular.component';
import { SearchComponent } from './search/search.component';
import { UserComponent } from './user/user.component';

export const appRoutes: Routes = [
    { path:'circular', component:CircularComponent },
    { path:'search', component:SearchComponent},
    { path:'user/:userId', component:UserComponent}
]
app.module.ts
import { HttpClientModule } from '@angular/common/http';
import { RouterModule } from '@angular/router';
import { appRoutes } from './app.routes';
.....

import: [
RouterModule.forRoot(appRoutes),
BrowserModule,
HttpClientModule
]

app.html


<router-outlet></router-outlet>       <!--  to implement router in our applicaiton -->

goto localhost:4200/search

find one result  and click
search.html
   <button  mat-button (click)="showUserDetails(user)">{{ user.login }}   </button>
  
search.component.ts
import { Router } from '@angular/router';
 showUserDetails(user){
    this.router.navigate(['user', user.login]);
  }

github.service.ts
.....

  getUserDetails(userId):Observable<any>{
    const url  = 'https://api.github.com/users/'+userId;
    return this.http.get(url).map(
      res =>{
        const user = res;
        return user;
      }
    )
  }
 
user.component.ts
import { ActivatedRoute } from '@angular/router';
....
private userDetail;

  constructor( private activatedRouter:ActivatedRoute, private githubService: GithubService) { }

  ngOnInit() {
    const userId = this.activatedRouter.snapshot.params['userId'];
    console.log(userId)
    this.githubService.getUserDetails(userId).subscribe(
      res =>{
        this.userDetail = res;
        console.log(this.userDetail)
      }
    )
  }
 
 
user.html
<h1>User Details page</h1>
<div *ngIf="userDetail">
  <h4>{{userDetail.name}}</h4>
  <p>email : {{userDetail.email}}</p>
  <small>followers: {{userDetail.followers}}</small>
</div>


Video:6 -> pipes, Debug angular 2, build for proeduction
----------
simple default pipes
<h4>{{userDetail.name | uppercase}}</h4>
  <p>email : {{userDetail.email}}</p>
  <small>followers: {{userDetail.followers}}</small>
  <p>created at:{{userDetail.created_at | date }}</p>
 
For Debugging:

Install chrome Augury plugin

 angular tree, state of the compoent, compoennt dependencies



Ref: ThatJsdude

Friday, 6 April 2018

Javascript - TicTacToe Game - Dynamic



<html>
<title>Tic Tac Toe</title>
<head>
<style>


*{
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box; 
  box-sizing: border-box;
}

select {
    padding:3px;
    margin: 0;
    -webkit-border-radius:4px;
    -moz-border-radius:4px;
    border-radius:4px;
    -webkit-box-shadow: 0 3px 0 #ccc, 0 -1px #fff inset;
    -moz-box-shadow: 0 3px 0 #ccc, 0 -1px #fff inset;
    box-shadow: 0 3px 0 #ccc, 0 -1px #fff inset;
    background: #f8f8f8;
    color:#888;
    border:none;
    outline:none;
    display: inline-block;
    -webkit-appearance:none;
    -moz-appearance:none;
    appearance:none;
    cursor:pointer;
    width:100px;
}


.minContainer {
    padding: 20px;
    padding-right: 30px;
    position: absolute;
}

table {
    border-collapse:collapse;
    table-layout: fixed;
    border-spacing: 0;
    width:250px;
    height:300px;
    margin-right:5px;
}
.td {
    border: 2px solid #cccccc;
    font-size:20px;
    font-family:"Helvetica Neue", Helvetica, Arial, sans-serif;
    color:#ccc;
    line-height: 1.428571429;
    width: 30px;
    height: 32px;
    min-width: 32px;
    max-width: 302px;
    min-height: 32px;
    max-height: 32px;
    text-align: center;
}

.X{
    background-color: #FF8362;   
}

.O{
    background-color: #BB7365;
}


</style>
</head>
<body onload="fnLoad()">
        <div class="container">
                <div>
                        <select id="grid">
                        </select>
                        <button name="NewGame" class="newGame" value="Start a New Game" onClick="fnNewGame()">Start a New Game</button>
                </div>
                <div class="minContainer">
                        <table class="row" id="game"></table>
                </div>
        </div>
<script>


var turn = 'X';
var score = {
    'X': 0,
    'O': 0
};
var gridValue = 0;

function fnLoad() {
    var select = document.getElementById("grid");
    for (i = 3; i <= 100; i += 1) {
        var option = document.createElement('option');
        select.options[select.options.length] = new Option(i + ' X ' + i, i);
    }

    addEvent(document.getElementById("game"), "click", fnChoose);

    fnNewGame();
}

function addEvent(element, eventName, callback) {

    if (element.addEventListener) {
        element.addEventListener(eventName, callback, false);
    } else if (element.attachEvent) {
        element.attachEvent("on" + eventName, callback);
    }
}

function fnChoose(e) {
    if (e.target && e.target.nodeName == "TD") {
        var targetElement = document.getElementById(e.target.id);
        var prevTurn;
        if ((targetElement.className).indexOf("disabled") == -1) {
            targetElement.innerHTML = turn;
            targetElement.classList.add('disabled');
            targetElement.classList.add(turn);
            score[turn] += 1;
            prevTurn = turn;
            turn = turn === "X" ? "O" : "X";
            if (fndecide(targetElement, prevTurn)) {
                alert(prevTurn + ' has won the game');
                fnNewGame();
            } else if ((score['X'] + score['O']) == (gridValue * gridValue)) {
                alert('Draw!');
                fnNewGame();
            }
        }
    }
}

function fndecide(targetElement, prevTurn) {
    var UL = document.getElementById('game');
    var elements, i, j, cnt;
    if (score[prevTurn] >= gridValue) {
        var classes = targetElement.className.split(/\s+/);
        for (i = 0; i < classes.length; i += 1) {
            cnt = 0;
            if (classes[i].indexOf('row') !== -1 || classes[i].indexOf('col') !== -1 || classes[i].indexOf('dia') !== -1) {
                elements = UL.getElementsByClassName(classes[i]);
                for (j = 0; j < elements.length; j += 1) {
                    if (elements[j].innerHTML == prevTurn) {
                        cnt += 1;
                    }
                }
                if (cnt == gridValue) {
                    return true;
                }
            }
        }
    }
    return false;
}

function fnNewGame() {
    var gameUL = document.getElementById("game");
    if (gameUL.innerHTML !== '') {
        gameUL.innerHTML = null;
        score = {
            'X': 0,
            'O': 0
        };
        turn = 'X';
        gridValue = 0;
    }
    var select = document.getElementById("grid");
    gridValue = select.options[select.selectedIndex].value;
    var i, j, li, k = 0,
        classLists;
    var gridAdd = +gridValue + 1;

    for (i = 1; i <= gridValue; i += 1) {
        tr = document.createElement('tr');
        for (j = 1; j <= gridValue; j += 1) {
            k += 1;
            li = document.createElement('td');
            li.setAttribute("id", 'li' + k);

            classLists = 'td row' + i + ' col' + j;

            if (i === j) {
                classLists = 'td row' + i + ' col' + j + ' dia0';
            }

            if ((i + j) === gridAdd) {
                classLists = 'td row' + i + ' col' + j + ' dia1';
            }

            if (!isEven(gridValue) && (Math.round(gridValue / 2) === i && Math.round(gridValue / 2) === j))
                classLists = 'td row' + i + ' col' + j + ' dia0 dia1';

            li.className = classLists;
            tr.appendChild(li);

        }
        gameUL.appendChild(tr);
    }
}


function isEven(value) {
    if (value % 2 == 0)
        return true;
    else
        return false;
}

</script>       
</body>
</html>

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

Claude Code worflow

The Claude code task cycle 1. Gater context Reads files, explore projec structure, code base 2. Plan Break the task in to steps 3. Exe...