Friday 23 June 2017

NG4- Custom Pipe - filter

NG4- Custom Pipe | - ng1 filtering  - Angular 2 beta version system based code fyi
==================================
Custom Filter 
==============


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

Message:
<input type="text" [(ngModel)]="message">
<br> Translated: {{(message | translate) | nvl:'N/A'}}

Here >=> traslate and nvl are custome filetrs. Need use the same naem for filter @pipe ->name
translate.pipe.ts               ==> custome filter no1
------------------
import {Pipe, PipeTransform, Inject} from 'angular2/core';
import {MessageService} from '../service/message.service';

@Pipe({
  name: 'translate',
  pure: false
})
export class TranslatePipe  implements PipeTransform{

private messageBundle:any;
private request:any;
    
    constructor(private _messageService: MessageService){
        this._messageService = _messageService;
        this.messageBundle = {};
    }
    
    transform(value:string, args:string[]):any {           // transform is the expected conversion method
        if(!this.request){
            this.request = this._messageService.getBundle();
            this.request.subscribe(
                data => this.messageBundle = data
             );
        }
        
        return this.messageBundle[value];
    }
}

nvl.pipe.ts                  ==> custome filter 2
-------------
import {Pipe, PipeTransform} from 'angular2/core';

@Pipe({
  name: 'nvl',
  pure: true
})
export class NvlPipe  implements PipeTransform{
    
    constructor(){}
    
    transform(value:string, args:string[]):any {
        return value?value : args[0];
    }
}


app.component.ts
------------------
import {Component} from 'angular2/core';
import {TranslatePipe} from './pipe/translate.pipe';
import {NvlPipe} from './pipe/nvl.pipe';

@Component({
  selector: 'app-component',
  templateUrl: 'src/app.component.tpl.html',
  pipes: [TranslatePipe, NvlPipe]
})
export class AppComponent {}

message.service.ts
-----------------------
import {Injectable} from "angular2/core"
import {Http} from 'angular2/http';
import 'rxjs/Rx'

@Injectable()
export class MessageService{
    constructor(http: Http){
        this.http = http;
    }
    getBundle (){
        return this.http.get('./src/bundle.json').map(res => res.json());
    }
}






index.html
------------
<!DOCTYPE html>
<html>

<head>
    <title>Custom Pipe Example</title>

    <!-- libraries -->
    <script src="https://rawgithub.com/systemjs/systemjs/0.19.6/dist/system.js"></script>
    <script src="https://code.angularjs.org/tools/typescript.js"></script>
    <script src="https://code.angularjs.org/2.0.0-beta.0/angular2-polyfills.js"></script>
    <script src="https://code.angularjs.org/2.0.0-beta.0/Rx.js"></script>
    <script src="https://code.angularjs.org/2.0.0-beta.0/angular2.dev.js"></script>
    <script src="https://code.angularjs.org/2.0.0-beta.0/http.dev.js"></script>

    <script>
        System.config({
            transpiler: 'typescript',
            typescriptOptions: {
                emitDecoratorMetadata: true
            },
            packages: {
                'src': {
                    defaultExtension: 'ts'
                }
            }
        });

    </script>

    <script>
        System.import('src/boot');

    </script>

</head>

<body>
    <app-component>Loading...</app-component>
</body>

</html>

CSS3 - Focus input animation effects - half -vertical border

 CSS3 - Focus input animation effects - half -vertical border
 ============================================================

 <body>
 <div class="input-wrapper">
  <input type="text" class="inputText" required/>
  <span class="floating-label">Your email address</span>
</div>
</body>

<style>
input:focus ~ .floating-label,
input:not(:focus):valid ~ .floating-label{
  top: 8px;
  bottom: 10px;
  left: 20px;
  font-size: 11px;
  opacity: 1;
}


.floating-label {
  position: absolute;
  pointer-events: none;
  left: 20px;
  top: 18px;
  transition: 0.2s ease all;
}
.input-wrapper {
  position: relative;
}
input{
font-family: Helvetica, Arial, sans-serif;
  font-weight: 300;
  width: 300px;
  border-radius: 2px;
  border: none;
  padding-left: 7px;
  height: 34px;
  font-size: 14px;
  color: #aaa;
  margin-top: 10px;
  margin-bottom: 5px;
}
input:focus {
  outline: none;
  box-shadow: none;
}
.input-wrapper:after {
  position: absolute;
  border: 1px solid #ccc;
  border-top: none;
  height: 5px;
  width: 100%;
  bottom: 6px;
  left: 0;
  content: "";
}
body{width:300px;}

</style>

NG4 - http-DELETE = DELETE Data Access service

NG4 - http-DELETE = DELETE Data Access service
=========================================
import { Component,Output,OnInit,Input, EventEmitter } from '@angular/core'

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

@Component({
selector:'deleteHttp',
styleUrls: ['./deleteHttp.scss'],
templateUrl: './deleteHttp.html',
})

export class DeleteHttpComponent implements OnInit{

...
constructor(private productService: ProductService) { }
...
deleteProduct(id: number): void {
this.productService.postProduct(id)
.subscribe(
(product: IProduct) => this.onProductRetrieved(product),  
// ---> Instead of this (data:any)=>{ if(data.success){ //true } else { //false }}
(error: any) => this.errorMessage= <any>error
);
}



postProduct.service.ts
----------------------
...
import { Http, Response} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';


...
@Injectable()
exportclassProductService{
privatebaseUrl= 'www.myWebService.com/api/products';
constructor(privatehttp: Http) { }
deleteProduct(id: number): Observable<Response> {
letheaders = newHeaders({ 'Content-Type': 'application/json'});
letoptions = newRequestOptions({ headers: headers });
consturl= `${this.baseUrl}/${id}`;
return this.http.delete(url, options);
}
}
private extractData(res: Response) {
    let body = res
    return body || {} ;
  }
   private handleError (error: any) {
    // In a real world app, we might use a remote logging infrastructure
    // We'd also dig deeper into the error to get a better message
    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);
  }

NG4 - http- UPDATE = UPDATE Data Access service

NG4 - http- UPDATE = UPDATE Data Access service
=========================================
import { Component,Output,OnInit,Input, EventEmitter } from '@angular/core'

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

@Component({
selector:'updateHttp',
styleUrls: ['./updateHttp.scss'],
templateUrl: './updateHttp.html',
})

export class UpdateHttpComponent implements OnInit{

...
constructor(private productService: ProductService) { }
editProduct: void {
this.productService.updateProduct(p)
.subscribe(
() => this.onSaveComplete(),
(error: any) => this.errorMessage= <any>error
);
}
}

}

postProduct.service.ts
----------------------
...
import { Http, Response} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';


...
@Injectable()
exportclassProductService{
privatebaseUrl= 'www.myWebService.com/api/products';
constructor(privatehttp: Http) { }
updateProduct(product: IProduct): Observable<IProduct> {
letheaders = newHeaders({ 'Content-Type': 'application/json'});
letoptions = newRequestOptions({ headers: headers });

consturl= `${this.baseUrl}/${product.id}`;
return this.http.put(url, product, options)
            // post also we can do ,but for consdition based we trying http.put
.map(() => product).catch(this.handleError);
}
}

private extractData(res: Response) {
    let body = res
    return body || {} ;
  }
   private handleError (error: any) {
    // In a real world app, we might use a remote logging infrastructure
    // We'd also dig deeper into the error to get a better message
    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);
  }

NG4 - http-POST = POST Data Access service

NG4 - http-POST = POST Data Access service
=========================================
import { Component,Output,OnInit,Input, EventEmitter } from '@angular/core'

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

@Component({
selector:'postHttp',
styleUrls: ['./postHttp.scss'],
templateUrl: './postHttp.html',
})

export class GetHttpComponent implements OnInit{

...
constructor(private productService: ProductService) { }
...
postProduct(id: number): void {
this.productService.postProduct(id)
.subscribe(
(product: IProduct) => this.onProductRetrieved(product),
// ---> Instead of this (data:any)=>{ if(data.success){ //true } else { //false }}
(error: any) => this.errorMessage= <any>error
);
}

@Injectable()
exportclassProductService{
privatebaseUrl= 'www.myWebService.com/api/products';
constructor(privatehttp: Http) { }
createProduct(product: IProduct): Observable<IProduct> {
letheaders = newHeaders({ 'Content-Type': 'application/json'});
letoptions = newRequestOptions({ headers: headers });
return this.http.post(this.baseUrl, product, options)
.map(this.extractData).catch(this.handleError);
}
}
}

postProduct.service.ts
----------------------
...
import { Http, Response} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
...
@Injectable()
exportclassProductService{
privatebaseUrl= 'www.myWebService.com/api/products';
constructor(privatehttp: Http) { }
createProduct(product: IProduct): Observable<IProduct> {
letheaders = newHeaders({ 'Content-Type': 'application/json'});            
letoptions = newRequestOptions({ headers: headers });
return this.http.post(this.baseUrl, product, options)
.map(this.extractData);
}
}

private extractData(res: Response) {
    let body = res
    return body || {} ;
  }
   private handleError (error: any) {
    // In a real world app, we might use a remote logging infrastructure
    // We'd also dig deeper into the error to get a better message
    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);
  }

NG4 - http-GET = GET Data Access service

NG4 - http-GET = GET Data Access service 
=========================================
import { Component,Output,OnInit,Input, EventEmitter } from '@angular/core'

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

@Component({
selector:'getHttp',
styleUrls: ['./getHttp.scss'],
templateUrl: './getHttp.html',
})

export class GetHttpComponent implements OnInit{

...
constructor(private productService: ProductService) { }
...
getProduct(id: number): void {
this.productService.getProduct(id)
.subscribe(
(product: IProduct) => this.onProductRetrieved(product),    
// ---> Instead of this (data:any)=>{ if(data.success){ //true } else { //false }}
(error: any) => this.errorMessage= <any>error
);
}
getProduct.service.ts
----------------------
...
import { Http, Response} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()
exportclassProductService{
privatebaseUrl= 'www.myWebService.com/api/products';
constructor(privatehttp: Http) { }
getProduct(id: number): Observable<IProduct> {        
// ---> Instead of this Observable<any> using object 
consturl= `${this.baseUrl}/${id}`;
return this.http.get(url)                              
// http.get method in ng2 / 4 same
.map(this.extractData)
.catch(this.handleError);
}
}

private extractData(res: Response) {
    let body = res
    return body || {} ;
  }
   private handleError (error: any) {
    // In a real world app, we might use a remote logging infrastructure
    // We'd also dig deeper into the error to get a better message
    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);
  }

Thursday 22 June 2017

NG4- Move Input search while enter/non empty text box - Like google search

NG4- Move Input search while enter/non empty text box - Like google search
========================================================

template.html
-------------
   <form [ngClass]="{'googleSearchForm':emptyText,'googleSearchFormtextenter':!emptyText}">
   
   <input id="googleSearchFormChange"  name="googleSearchFormChange" [(ngModel)]="googleSearchFormChange"
        #box (keyup)="onKey(box.value)" type="text" [formControl]="term" autocomplete="off">

</form>

<SearchValuesResult> </SearchValuesResult>  //<-------so result will come top of page
component.ts
------------

import { component } from '@angular/core'
import { FormControl } from '@angular/forms'
import { FormsModule } from '@angular/forms';
import { Http, Response, Headers } from '@angular/http';


@compoent({

selector: '<searchbar',
templateUrl: ['template.html'],
stylrUrl:['templateStyle.css']

})

@Injectable()

export class SearchComponent {

emptyText = true;

constructor( private http: Http,){}

  onKey(value: string) {
    this.emptyText = false;

    if(this.term.value == ''){
      this.emptyText = true;
    }

}  // c;ass end

templateStyle.css
------------------

.googleSearchForm {
    width: 80%;
    position: relative;
    margin: auto auto 0 15%;
    padding-top: 26%;                      // ------> Empty while textbox is empty
    transition: 1s;
}
.googleSearchFormtextenter{
    padding-top: 13%;
    width: 80%;
   padding-top:10%;
    position: relative;                                  // not mentioned area of text box will display
    margin: auto auto 0 15%;
}

Tuesday 20 June 2017

NG2- Keyboard Event Demo - Typing keyboard event - HostListener

NG2- Keyboard Event Demo - Typing keyboard event - HostListener
==================================================
//our root app component
import {Component, HostListener} from 'angular2/core';

window.focus(); // make sure we are on this page before we start typing

@Component({
  selector: 'my-app',
 template: `
    <div>
      <h2>Keyboard Event demo</h2>
      Start typing to see KeyboardEvent values
    </div>
    <hr />
    KeyboardEvent
    <ul>
      <li>altKey: {{altKey}}</li>
      <li>charCode: {{charCode}}</li>
      <li>code: {{code}}</li>
      <li>ctrlKey: {{ctrlKey}}</li>
      <li>keyCode: {{keyCode}}</li>
      <li>keyIdentifier: {{keyIdentifier}}</li>
      <li>metaKey: {{metaKey}}</li>
      <li>shiftKey: {{shiftKey}}</li>
      <li>timeStamp: {{timeStamp}}</li>
      <li>type: {{type}}</li>
      <li>which: {{which}}</li>
    </ul>`
})
export class App {
  
  /* 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: https://plnkr.co/edit/Aubybjbkp7p8FPxqM0zx?p=preview

Tuesday 13 June 2017

NG2- Router in Angular 2 component

import { Router } from '@angular/router';

export class App
Component{


construcot(private router: Router) {
    this.windowSize = window.innerWidth;
    this.url = router.url.split('/');
    this.arraylength = this.url.length;
    this.category = this.url[this.arraylength - 2];
    this.uniqueId = unescape(this.url[this.arraylength - 1]);


}

}