Tuesday, 16 May 2017

NG2- How to add Javascript in Angular 2

NG2- How to add Javascript in Angular 2
--------------------------------------------------

We shouldn't directly include script in index.html

Solution-1 - Angular CLI- solution
-----------
Open Angular-cli.json 

add under script{ ""ScriptName": "JS file  path located in our application" }

Solution-2 - Other Ng application
-----------

Open the package.json 

add under script{ "ScriptName" :"Script npm path - name" }

Wednesday, 3 May 2017

NG2- Screen height and Width measure even resize of the screen Height

NG2- Screen height and Width measure even resize of the screen Height
====================================================

screenHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);

onResize(event) {
  event.target.innerWidth;
  this.screenHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
   
}

Ref: http://stackoverflow.com/questions/35527456/angular2-window-resize-event

Friday, 28 April 2017

NG2 - Confirmation Pop up show for Warning then Yes or No pop up confirmation

NG2 - Confirmation Pop up show for Warning then Yes or No pop up confirmation 
------------------------------------------------------------------------------

import the popup component and Confirmation-Popup into app.module.ts or required module

App.component.html
-------------------
...... app content

<popup  [close]="AlertPopupAlert" [popuptitle]="modaltitleMsg" [popupTxtMsg]= "modalMsgContent" (closepopupclicked)="closeAlertPopup($event)"></popup>

<confirmation-popup [confirmclose]="showConfirm" [confirmtitle]="confirmationTitle" [confirmsg]="confirmTxtMSg" (yesconfirmationclick)="Yesconfirm()" (noconfirmationClick)="NoConfirm()"></confirmation-popup>


App.component.ts
----------------
@Component({
})

export class AppComponent{

//popup 

AlertPopupAlert = true;
modaltitleMsg;
modalMsgContent;

successTrigger(){
this.AlertPopupAlert = false;
this.modaltitleMsg = "Success !";
this.modalMsgContent = " Operation Success ";
}
WaringTrigger(){
this.AlertPopupAlert = false;
this.modaltitleMsg = "Warning / Info/ Fail !";
this.modalMsgContent = " Operation Failed ";
}
closeAlertPopup(){
this.AlertPopupAlert = true;
this.modaltitleMsg = "";   // not required. For making different process clearing the text msg.
this.modalMsgContent = "";
}

//confirmation - popup   

showConfirm = true;
confirmationTitle;
confirmTxtMSg;

confrimationTrigger(){
this.confirmationTitle = "Warning !";
this.confirmTxtMSg = " Do you want to operation ?";
this.showConfirm = false;
}

Yesconfirm(){
this.AlertPopupAlert = false;
this.showConfirm = true;
this.modaltitleMsg = "Success !";
this.modalMsgContent = " Operation Success ";
}
NoConfirm(){
this.showConfirm = true;
this.confirmationTitle = "";
this.confirmTxtMSg = "";
}


}
 Confirmation-popup.component.html
--------------

End of component .// Be default popup should be disabled // check the the component z-index if component has to come top of all the div.-->

<div [hidden]="confirmclose" style=" z-index: 12; top: 30%; position: fixed; margin-left:25%; height: 20%;   width: 40%;     background: #fff;    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);" *ngIf="showPopup">
    <span style="float:left;"> {{ confirtitle }}</span> <span style="float:right;color:blue;padding-right:3px;padding-top:3px;cursor:pointer;" ((click)="closePopup()">X </span>
        <div> {{ confirmsg }}</div>

<div><span class="button popup-button" (click)="noconfirmation()">No</span>
            <span class="buttonpopup-button" (click)="yesconfirmation()">Yes</span>  
</div>
</div>

Confirmation.popup.ts
------------------------
export class ConfirmationPopUp implements OnChanges, OnInit {

  @Input() confirtitle:any = 'test';
  @Input() confirmsg:any = 'test';
  @Input() confirmclose = false;
  @Output() yesconfirmationclick = new EventEmitter();
  @Output() noconfirmationClick = new EventEmitter();
  constructor(){

  }

  yesconfirmation(){
    //this.close = true;
    this.yesconfirmationclick.emit(true);
  }
  noconfirmation(){
    this.noconfirmationClick.emit(true);
  }

  ngOnInit() {

  }
  ngOnChanges() {

  }
  keyboardEvent: any;    
@HostListener('window:keydown', ['$event'])
keyboardInput(event: any) {
this.keyboardEvent = event;
 if (event.keyCode == 27){
console.log("Esc Key press to clsoe current popup");
this.noluciconfirmation();
 }
}

}

popup.component.html
--------------

End of component .// Be default popup should be disabled // check the the component z-index if component has to come top of all the div.-->

<div [hidden]="close" style=" z-index: 12; top: 30%; position: fixed; margin-left:25%; height: 20%;   width: 40%;     background: #fff;    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);" *ngIf="showPopup">
    <span> {{ title }}</span> <span style="float:right;color:blue;padding-right:3px;padding-top:3px;cursor:pointer;" ((click)="closePopup()">X </span>
        <span> {{ ShowPopupMessage }}</span>
</div>

popup.component.ts
-------------
import { Component, Input, Output, OnChanges, OnInit, EventEmitter, ViewEncapsulation, HostListener } from '@angular/core';
@Component({
  selector: 'popup',
  templateUrl: './component.html',
  styleUrls: ['./component.css'],
  encapsulation: ViewEncapsulation.None   
})

export class Popup implements OnChanges, OnInit{
  

  @Input() title:any = 'test';     
  @Input() ShowPopupMessage:any = 'test';
  @Input() close = false;
  @Output() closepopupclicked = new EventEmitter();
  
  closePopup(){
    //this.close = true;
    this.closepopupclicked.emit(true);
  }
  
   ngOnInit() {

  }
  
  // @input and out put is required the ngOnChanges () life cycle function
  ngOnChanges() {

  }
  
  // ESC key press to close the popup 
  
  keyboardEvent: any;    
@HostListener('window:keydown', ['$event'])
keyboardInput(event: any) {
this.keyboardEvent = event;
 if (event.keyCode == 27){
console.log("Esc Key press to clsoe current popup");
this. closePopup();
 }
}



}

NG2 - Pop up show for success / Warning / info across App / Component based

NG2 - Pop up show for success / Warning / info across App
-----------------------------------------------------------

import the popup component into app.module.ts 

App.component.html
-------------------

<popup  [close]="AlertPopupAlert" [popuptitle]="modaltitleMsg" [popupTxtMsg]= "modalMsgContent" (closepopupclicked)="closeAlertPopup($event)"></popup>

App.component.ts
----------------
@Component({
})

export class AppComponent{

AlertPopupAlert = true;
modaltitleMsg;
modalMsgContent;

successTrigger(){
this.AlertPopupAlert = false;
this.modaltitleMsg = "Success !";
this.modalMsgContent = " Operation Success ";
}
WaringTrigger(){
this.AlertPopupAlert = false;
this.modaltitleMsg = "Warning / Info/ Fail !";
this.modalMsgContent = " Operation Failed ";
}
closeAlertPopup(){
this.AlertPopupAlert = true;
this.modaltitleMsg = "";   // not required. For making different process clearing the text msg.
this.modalMsgContent = "";
}
}

popup.component.html
--------------

End of component .// Be default popup should be disabled // check the the component z-index if component has to come top of all the div.-->

<div [hidden]="close" style=" z-index: 12; top: 30%; position: fixed; margin-left:25%; height: 20%;   width: 40%;     background: #fff;    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);" *ngIf="showPopup">
    <span> {{ title }}</span> <span style="float:right;color:blue;padding-right:3px;padding-top:3px;cursor:pointer;" ((click)="closePopup()">X </span>
        <span> {{ ShowPopupMessage }}</span>
</div>

component.ts
-------------
import { Component, Input, Output, OnChanges, OnInit, EventEmitter, ViewEncapsulation, HostListener } from '@angular/core';
@Component({
  selector: 'popup',
  templateUrl: './component.html',
  styleUrls: ['./component.css'],
  encapsulation: ViewEncapsulation.None   
})

export class Popup{
  

  @Input() title:any = 'test';     
  @Input() ShowPopupMessage:any = 'test';
  @Input() close = false;
  @Output() closepopupclicked = new EventEmitter();
  
  closePopup(){
    //this.close = true;
    this.closepopupclicked.emit(true);
  }
  
   ngOnInit() {

  }
  
  // @input and out put is required the ngOnChanges () life cycle function
  ngOnChanges() {

  }
  
  // ESC key press to close the popup 
  
  keyboardEvent: any;    
@HostListener('window:keydown', ['$event'])
keyboardInput(event: any) {
this.keyboardEvent = event;
 if (event.keyCode == 27){
console.log("Esc Key press to clsoe current popup");
this. closePopup();
 }
}



}

NG2- Video Play in Popup / Play you tube video also in using in iframe in pop up

NG2- Video Play in Popup  (click the link)
==========================

Play you tube video also in using in iframe

step:1
------
Add the videoView.mp4 file in ProjectFolder/App/src/ or some build not affected place.

stpe:2
-------

component.html
--------------
<div (click)="showSaleVideo()"> Play video as popup in Angular 2 </div>

--> end of component add popup div

<div style=" z-index: 12; top: 30%; position: fixed; margin-left:25%; height: 50%;   width: 50%;     background: #fff;    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);" *ngIf="videoPlay">
    <span style="float:right;color:blue;padding-right:3px;padding-top:3px;cursor:pointer;" (click)="CloseVideoPlay()"> X </span>
        <div>           
           <video width="100%" height="100%" controls>
                <source src="Videorview.mp4" type="video/mp4">  
                Your browser does not support the video tag.
            </video>
<!-- Video in iFrame from You tube
<iframe width="100%" height="100%" src="https://www.youtube.com/embed/XGSy3_Czz8k"></iframe> -->
        </div>
</div>


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


@Component({
  selector: 'popup-model-video',
  templateUrl: './component.html',
  styleUrls: ['./component.css'],
  encapsulation: ViewEncapsulation.None    <-- not required 
  
})
export class PopupModelVideoComponent implements OnInit{


constructor(){}

videoPlay = false;

showSaleVideo(){
this.videoPlay = true;
}
CloseVideoPlay(){
this.videoPlay = false;
}

}


==========

html video play:
---------------
<html>

<body>

<!-- Video in iFrame -->
<iframe width="420" height="345" src="https://www.youtube.com/embed/XGSy3_Czz8k"></iframe>

    <!-- Video in video control  -->
    <video width="100%" height="100%" controls>
<source src="Videoview2.mp4" type="video/mp4">  
Your browser does not support the video tag.
</video>
</body>

</html>

Tuesday, 25 April 2017

NG2- Press escape close - the popup / Do coustom function

NG2- Press escape close - the popup / Do custom function
==========================================================

import{  Component,HostListener } from '@angular/core'

@Component({
  selector: 'my-app',
 template: 'my-app.html"
 })
export class myapp {

 keyboardEvent: any;
 @HostListener('window:keydown', ['$event'])
   keyboardInput(event: any) {
this.keyboardEvent = event;
 if (event.keyCode == 27){
console.log("Esc Key press to clsoe current popup");

 }
}
  /* a few examples */
  keyboardEvent: any;
  altKey: boolean;
  charCode: number;
  code: string;
  ctrlKey: boolean;
  keyCode: number;
  keyIdentifier: string;
  metaKey: boolean;
  shiftKey: boolean;
  timeStamp: number;
  type: string;
  which: number;
  
  @HostListener('window:keydown', ['$event'])
  keyboardInput(event: any) {
    event.preventDefault();
    event.stopPropagation();
    
    this.keyboardEvent = event;
    this.altKey = event.altKey;
    this.charCode = event.charCode;
    this.code = event.code;
    this.ctrlKey = event.ctrlKey;
    this.keyCode = event.keyCode;
    this.keyIdentifier = event.keyIdentifier;
    this.metaKey = event.metaKey;
    this.shiftKey = event.shiftKey;
    this.timeStamp = event.timeStamp;
    this.type = event.type;
    this.which = event.which;
  }
  
}

/**
a list of values available via KeyboardEvent
  altKey: boolean
  bubbles: boolean
  cancelBubble: boolean
  cancelable: boolean
  charCode: number
  code: string
  ctrlKey: boolean
  currentTarget: null
  defaultPrevented: boolean
  detail: number
  eventPhase: number
  isTrusted: boolean
  isTrusted: boolean
  keyCode: number
  keyIdentifier: string
  keyLocation: number
  location: number
  metaKey: boolean
  path: array
  repeat: boolean
  returnValue: boolean
  shiftKey: boolean
  sourceCapabilities: string
  srcElement: any
  target: any
  timeStamp: number
  type: string
  view: string
  which: number
*/

Ref: http://stackoverflow.com/questions/36695922/angular-2-keyboard-events

Friday, 7 April 2017

NG2- Custom Validation function for empty space checking.

NG2- Custom Validation function for empty space checking.
============================================
component.html
==============
<input type="text" [formControl]="NameCtrl" placeholder="Enter New name">
<div *ngIf="NameCtrl.touched" style="color:brown">
<span *ngIf="NameCtrl.status == 'INVALID'"> Enter  Name</span>
</div>
  
component.ts
==============
  
NameCtrl = new FormControl('', [Validators.required, this.NoWhitespaceValidator])


public NoWhitespaceValidator(control: FormControl) {
    let isWhitespace = (control.value || '').trim().length === 0;
    let isValid = !isWhitespace;
    return isValid ? null : { 'whitespace': true }
}

Saturday, 25 March 2017

NG2-ScrollToTop PAGE-every router change(url change)

NG2-ScrollToTop PAGE-every router change(url change)

Componet.ts
============
import {ChangeDetectionStrategy, Component } from '@angular/core'
import { ActivatedRoute,Router } from '@angular/router'


@Component({
  selector: 'rootcomponent',
.....

export class Rootcomponent{
  searchChange;
constructor( _router: Router){

_router.events.subscribe((val) => {
this.searchChange = '';   // change text box value as empty every router change
window.scrollTo(0,0);
}
this.searchChange = somevalue

}

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

<input type="text" value="{{ searchChange }}">

NG2- Pass data from child to parent (reverse also) components

NG2- Pass data from child to parent (reverse also) components
=============================================
parent.components.ts
---------------------
....
import { Component, Input, EvenEmitter } from '@angular/core'
....
export class parentCompoent implements OnInit {
  // no need of @input for one way data pass
   ShowCustomPopup= true // hidden by default true
   ....
   
   ShowCustomPopup(){
    this.ShowCustomPopup=false;
  }
  closeCustomPopupModol(event){
    this.ShowCustomPopup= true;
  }

}

parent.template.html
----------------------
.....
<div (click)="ShowCustomPopup()"> Open Popup </div>
....
    <childComponent [hidden]="ShowCustomPopup" (clospopup)="closeCustomPopupModol(event)"></childComponent>
....
....


Child.components.ts
---------------------
....
import { Component, Input, EvenEmitter } from '@angular/core'
// boolean value is going to pass 

//closepop -> click or close function of child modal

@Output() clospopup : EventEmitter<any>= new EventEmitter();

ClosechildPopup(){
console.log("clooooose icon in child component pass to parent components ")

this.clospopup.emit(true);

}
childComponent.template.html
----------------------------

<div class="panel">
<div class="panel-head pull-right" (click)="ClosechildPopup()"> X (close) </div>
</div>

@hint : child popup is the custom Popup of Parent component.

NG2-Component-service-json

mycomponent.component.ts
========================
import { Component,ViewEncapsulation, OnInit } from '@angular/core'
import { Router } from '@angular/router';
import { mycomponentService } from './MycomponentService.service'
 @component({
 ....
 .....})

 export class MycomponentComponent implements OnInit {

 this.urldetails = this.router.parseUrl(this.router.url);
    this.url = router.url.split('/');


constructor( private)

this._mycomponentService.getList(this.url).subscribe(
      (data: any) => {
 if(data.success == true){
 console.log("sucess", data.rows.);
 }
 esle{
 console.log("Fail response",)
 }

 },(error:any) => {
      console.log("Error HTTP GET Service",error)
      });



 }
mycomponent.service.ts
======================

import {Injectable} from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import 'rxjs/add/operator/catch';
import { Observable } from 'rxjs/Observable';



@Injectable()
export class ConfigurationService {
  constructor(private http: Http) {
  }
  url = "http://mydomain.com/serviceAPI/"

  getList(...args){
  var argslength=args[0].length;
  var argID = args[0][argslength-2]


  return this.http.get(this.url+"/argID")
  .map(this.extractData)
  .catch(this.handleError);
  }

   private extractData(res: Response) {
    let body = res.json();
    return body || { };
  }

   private handleError (error: any) {
    let errMsg = (error.message) ? error.message :
    error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    console.error(errMsg); // log to console instead
    return Observable.throw(errMsg);
  }

  }

NG2- Observables - Subject js- promises

NG2- Observables - Subject js- promises
=============================
components.ts
--------------
import { Subject } from 'rxjs';

export class Mycomponents {

postCall = new Subject();

this.checkPostisTrue(getChecklist);   // once it returns true
this.postCustomGroup(postdata);        // then it should execute. wait until $ deffered


checkPostisTrue(data){

this._MyService.checkPost(data).subscribe( (data:any) => {   // get service method
if(data == true){   //someother condition
this.postCall.next(true);   // true is passing data. May be array any,string type

}
}
}

postCustomGroup(post){
this._MyService.PostPromiseData(data).subscribe( (data:any) => { 

}


}


}

KISS, DRY, SOLID, YAGNI — A Simple Guide to Some Principles of Software Engineering and Clean Code

1 — KISS (Keep It Simple, Stupid)  Simplicity triumphs over complexity. Direct and clear codes are better for developing, maintaining, and s...