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) => { 

}


}


}

NG2- Post data as Form Data - Payload method

NG2- Post data as Form Data control method 
NG2- Post data as Payload format 
================================

myform.compoent.ts
===================
import { Component } from '@angular/core'
import { FormControl, NgForm, Validator, Validators } from '@angular/forms';
import { PasswordResetService } from './PasswordResetService.service'

@component({
selector: 'password-reset-form',
styles: [require('./Style.css')],
template: require('./myform.template.html')

})

export class PasswordResetComponent{

oldPasswordCtrl = new FormControl();
construtor(service: PasswordResetService){

}
PostFormData(){
let postData = { postDataKey : oldPasswordCtrl }  // Make JSON format for form-data

this.service.postFormData(postData).subscribe ( (data => any) {
if(data.status){ 'true' } else { 'false '}
}
}
PostPayLoad(){
let postData = `postDataKey=oldPasswordCtrl`  // Make string format for payload
//`key1=value1&key2=value2`

this.service.postPayload(postData).subscribe ( (data => any) {
if(data.status){ 'true' } else { 'false '}
}
}

}

import {Injectable} from '@angular/core';
import { Http, Response, Headers } from '@angular/http';

@Injectable()
export class PasswordResetService {
  constructor(private http: Http) {
  }
  PostUrl = 'http://mydomain/postAPI';
  
  postFormData(data){
return this.http.post(PostUrl, data).map( response => response.json())
  }
  postPayload(data){
  return this.http.post(PostUrl, data).map( response => response.json())
  }
  

tempalte.html
---------------
<input  [formControl]="oldPasswordCtrl" >

NG2- Reactive Form - validation using FormControl

NG2- Reactive Form - validation using FormControl
======================================
myform.template.html
================

<div class="login-form">
<!-- No need of Tag start with <form> and if edit mode of the form  [(ngModel)] 2 way data binding.
<div class="username">
<input  [formControl]="userNameCtrl" >
<div *ngIf="userNameCtrl.touched" style="color:brown">
<span *ngIf="userNameCtrl.status == 'INVALID'">    Enter User name </span>
</div>
</div

<div class="password">
<input  [formControl]="password" >
<div *ngIf="password.touched" style="color:brown">
<span *ngIf="password.status == 'INVALID'">    Enter Password </span>
</div>
</div> 
<div class="form-submit">
<span [ngClass]="{'button disableCGbtn': password.status == 'INVALID' || userNameCtrl.status == 'INVALID' , 
'button ': password.status == 'VALID' && userNameCtrl.status == 'VALID' }" (click)="SubmitLogin()"> SUBMIT</span>
 
<span class="button" (click)="ClosecreateNewCustomGroup()">Cancel</span>
<div class="loginfail" *ngIf="loginFail"> Login failed. Try Again </div>  
</div>
</div <!-- form div end -->

 Style.css   --> disable css property for buttons 
-----------
{
 opacity: 0.5;
 pointer-events: none;

myform.compoent.ts
==============
import { Component } from '@angular/core'
import { FormControl, NgForm, Validator, Validators } from '@angular/forms';

@component({
selector: 'login-form',
styles: [require('./Style.css')],
template: require('./myform.template.html')

})

export class MyformComponent {

loginSucess:private;
loginfail:private;
userNameCtrl = new FormControl('',Validators.required);
constructor( private router: Router, private _loginService: :LoginService){
this.loginfail = false;
}
SubmitLogin(){
let usernameValue = this.userNameCtrl.value;
let passwordValue = this.password.value;

// if post body as pay-load -> create string format data to post
let postCredential = `username=${usernameValue}&password=${passwordValue}` 
// if post body as form-data  -> create JSON object formta data to post
let postCredential { username: usernameValue, password: passwordValue }

this._loginService.login(postCredential).subscribe( (data=>any) {
if(data.status == "true" ){
console.log("Login success")
this.loginfail = false;
this.loginSucess = true;
let userid = data.userID;

let redirectURL = 'homepage/userpage/'+userid+'/page1';
this.router.navigate([url]);
//this.usernameValue.setValue(data.userFullName) ->ngModel replacement not relate to login

}
else {
console.log("login Failed")
this.loginfail = true;
this.loginSucess = false;
}

}
}  // login method end
}  // compoent end

NG2-To convert the data in NG2 using data default format

NG2-To convert the data in NG2 using data default format
--------------------------------------------------------

"2017-02-18T07:43:00-05:00"


{{lastupdate |  date:'EEE, d MMM,y hh:mm:ss'}}

JS- Split the string with comma (,) make as array,detect missing item (sorting),arrya to string

JS- Split the string with comma (,) make as array 
JS- Compare two array have same value - detect missing item (sorting)
JS - array to string

var SerialArry = "123,13, 1234";
var ResponseArry = "123,1234";

SerialArry =SerialArry.split(",");
for(var i=0; i<SerialArry.length; i++) { 
SerialArry[i] = +SerialArry[i]; // [123,13,1234]
}
SerialArry = SerialArry.sort();


ResponseArry = ResponseArry.split(",");
for(var i=0; i<ResponseArry.length; i++) {
ResponseArry[i] = +ResponseArry[i]; // [123,1234]
}
ResponseArry = ResponseArry.sort();


var InvalidNo = SerialArry.filter(function(x) 
{ return ResponseArry.indexOf(x) < 0 }); // missing number from response array


SerialArry = SerialArry.toString(); // convert Array to String
ResponseArry = ResponseArry.toString();
if(SerialArry == ResponseArry) {
console.log('true'); // request & response  same and true


}
else {
console.log('false') // request & response false not same

}

JS- Remove White space and retain New line character,spl char not allow

Javascript - Remove White space  and retain New line character,spl char not allow
===========================================================

function RemoveallSpaces() {
    var output = document.getElementById("content").value;          // textarea or text .....

    output = output.replace(/\s/g, "") // remove all spl characters

output = /[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(output)     //retain new line chars

    document.getElementById("output").innerHTML = output;
}


Direct second point

output = output.replace(/[ \t]/g,'');                              // textarea or text .....

function isValid(str){
return !/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);    //special character not allow 

}