Monday 26 December 2016

NG2-Two way data binding - Searc Text Filter list of item in Array

NG2-Two way data binding - Searc Text Filter list of item in Array
============================================
Template.html
-------------

<div class="panel-default">
<div class="panel-heading">All list Data
<div>
<input [ngModel]="sectionSearch" (ngModelChange)="onSearchSection($event)" class="sidesearch" placeholder="Search...">
</div>
</div>
<div class="panel-body allDataList">
<div *ngFor="let item of alldata" routerLinkActive="active"><a routerLink="DomainSecondURL/{{item.displayName}}">{{item.displayName}}</a>
</div>
</div>
</div>


Component.ts
-------------

import {Component,ViewContainerRef,ViewEncapsulation, OnInit} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import { FormControl } from '@angular/forms';

@Component({
selector:'template',
template:require('./template.html')
})

export class FilterData{

public allData:any;
public filterData:any;


constructor(private route:ActivatedRoute,private allDataService:AllDataService, private router: Router){
this.url = router.url.split('/');
this.AllDataService.getleftmenuData(this.url)  
.subscribe(
(data:any)=>{    

this.allData= data.sections;
this.filterData = this.allData;

},
(error:any)=>{
console.log("error");
}
);      
}
onSearchSection(event:Event) {

this.allData = this.filterData.filter(
section => section.displayName.toLocaleLowerCase().indexOf(event) >= 0

// {section => Obj.propeName - displayName}
);

}

}

NG2- forloop and View to Component with Services

Ng2- forloop and View to Component with Services
================================================
Data render from Componet service
----------------------------------

Datatemplate.html
--------------
<div class="panel-body">
<div *ngFor="let item of allData" routerLinkActive="active">
<a routerLink="allData/{{item.displayName}}">{{item.displayName}}</a>
</div>
</div>

Datacomponent.ts
-----------------

import {Component,ViewContainerRef,ViewEncapsulation, OnInit} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {DataService} from './asupDetailsSideBar.service';

export class DataComponet{

public allData: any;

constructor(private route:ActivatedRoute,private dataService:DataService, private router: Router){

this.dataService.getData(Key)
.subscribe(
(data:any)=>{
this.allData = data.Data;
},
(error:any)=>{
console.log("error");
}
);
}
}

DataService.ts
---------------

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

@Injectable()
export class AsupDetailsSideBarService {

constructor(private http: Http) {

 }
    getData(...args): Observable<any>{

    var argslength=args[0].length;
    let serialNumber=args[0][argslength-3];
 
    let staticUrl=`http://domain/api/serviceCall(key)`;  
 
    return this.http.get(this.staticUrl).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);
  }
 }

Saturday 10 December 2016

NG2 - ToggleStyle-Apply from components:

ng2-ToggleStyle-Apply from components:
-------------------------------------

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

//our root app component
import { NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {Component} from '@angular/core';

// while using [ngdirective] import FomrsModule in your app.module.ts

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <div [ngClass]="{'my-class': isClassVisible }">
        I'm a div that wants to be styled
      </div>
      <button (click)="isClassVisible = !isClassVisible;">Toggle style</button>
    </div>
  `,
  styles: [
  `
  .my-class {
    background-color: yellow;
  }
  `
  ]
})
class App {
  isClassVisible: false;

  constructor() {
  }

}

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

NG2 - selectAllNotSelected-Checkbox

thanx - for Ref:
http://stackoverflow.com/questions/34219199/angular2-how-to-get-all-selected-check-boxes

.html
--------

<button value="all" (click)="bulk('all')">ALL</button>
<button value="none" (click)="bulk('none')">NONE</button>

<div *ngFor="#students of student_list #i=index">
  <input type="checkbox" value={{students.id}} class="checkedStudent"
  (change)="checkedStudents(students.id)" id={{students.id}}>
</div>

.ts
-----

abc:Array<any>= [];
checkedStudents(value) {
        console.log(value);
        if ((<HTMLInputElement>document.getElementById(value)).checked === true) {
            this.abc.push(value);
        }
        else if ((<HTMLInputElement>document.getElementById(value)).checked === false) {
            let indexx = this.abc.indexOf(value);
            this.abc.splice(indexx,1)
        }
        console.log(this.abc)
    }

// for Bulk actions

bulk(a) {
        // console.log(a);
        if (a == "all") {
            console.log("yes all");
            this.abc = [];
            for (let i = 0; i < this.student_list.length; i++) {
                (<HTMLInputElement>document.getElementsByClassName("checkedStudent")[i]).checked = true;
                this.abc.push(this.student_list[i].id);
            }
        }
        if (a == "none") {
            for (let i = 0; i < this.student_list.length; i++) {
                (<HTMLInputElement>document.getElementsByClassName("checkedStudent")[i]).checked = false;
            }
            this.abc = [];
        }
        console.log(this.abc);
    }

NG2 - Pagination- Web pack

ng2-Pagination:
----------------
Ref: http://michaelbromley.github.io/ng2-pagination/#/

npm install ng2-pagination --save

// app.module.ts
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {Ng2PaginationModule} from 'ng2-pagination'; // <-- import the module
import {MyComponent} from './my.component';

@NgModule({
    imports: [BrowserModule, Ng2PaginationModule], // <-- include it in your app module
    declarations: [MyComponent],
    bootstrap: [MyComponent]
})
export class MyAppModule {}



// my.component.ts
import {Component} from '@angular/core';

@Component({
    selector: 'my-component',
    template: `
    <ul>
      <li *ngFor="let item of collection | paginate: { itemsPerPage: 10, currentPage: p }"> ... </li>
    </ul>

    <pagination-controls (pageChange)="p = $event"></pagination-controls>
    `
})
export class MyComponent {
    public collection: any[] = someArrayOfThings;
}


Plukr ref: http://plnkr.co/edit/JVQMPvV8z2brCIzdG3N4?p=preview

Friday 9 December 2016

Ng2-highcharts

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { NgModule, Component }    from '@angular/core';
import { BrowserModule }          from '@angular/platform-browser';
import { ChartModule }            from 'angular2-highcharts';

@Component({
    selector: 'my-app',
    styles: [`
      chart {
        display: block;
      }
      button {
        display: block;
        width: 100%;
        height: 25px;
      }
  `],
    template: `
        <chart [options]="options" (load)="saveChart($event.context)">
          <series (hide)="onSeriesHide($event.context)">
            <point (select)="onPointSelect($event.context)"></point>
          </series>
        </chart>
        <button (click)="addPoint()">Click to add random points</button>
    `
})
class AppComponent {
    constructor() {
        this.options = {
            title : { text : 'angular2-highcharts example' },
            series: [{
                name: 's1',
                data: [2,3,5,8,13],
                allowPointSelect: true
            },{
                name: 's2',
                data: [-2,-3,-5,-8,-13],
                allowPointSelect: true
            }]
        };
    }
    options: Object;
    chart: Object;
    saveChart(chart) {
      this.chart = chart;
    }
    addPoint() {
      this.chart.series[0].addPoint(Math.random() * 10);
      this.chart.series[1].addPoint(Math.random() * -10);
    }
    onPointSelect(point) {
      alert(`${point.y} is selected`);
    }
    onSeriesHide(series) {
      alert(`${series.name} is selected`);
    }
   
}

@NgModule({
  imports:      [BrowserModule, ChartModule],
  declarations: [AppComponent],
  bootstrap:    [AppComponent]
})
class AppModule { }


platformBrowserDynamic().bootstrapModule(AppModule);

Ng2-highcharts - Webpack installation:

Ng2-highcharts - Webpack installation:
-------------------------------------
Ref: https://www.npmjs.com/package/angular2-highcharts#installation

npm install angular2-highcharts --save

setuo App.module:->
--------------------

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ChartModule } from 'angular2-highcharts';
import { App } from './App';

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

Component.ts:
-------------

import { Component } from '@angular/core';

@Component({
    selector: 'simple-chart-example',
    template: `
        <chart [options]="options"></chart>
    `
})
export class App {
    constructor() {
        this.options = {
            title : { text : 'simple chart' },
            series: [{
                data: [29.9, 71.5, 106.4, 129.2],
            }]
        };
    }
    options: HighchartsOptions;
}

NG2- Default Checkbox true and change Checkbox selection values:

NG2- Default Checkbox true and change Checkbox selection values:
----------------------------------------------------------------



Ref:http://plnkr.co/edit/Hxy5Jz?p=preview

@Component({

 selector: 'my-app',

  providers: [],



 template: `
  <div>
 
 
      <input type="checkbox" [checked]="isAvailable" (change)="isAvailable = $event.target.checked">

     <pre>{{ isAvailable | json }}</pre>

    </div>
  `,

 directives: []
})


export class App {

 isAvailable = true;
 
constructor() {
   
  }

}

NG2-applyCSScontion based

<tr *ngFor="let rowdata of TableRows">
          <td><a routerLink="{{rowdata.sysid}}">{{rowdata.date}}</a></td>      --> link to route
          <td [class.mycls]=getclass(rowdata)>  {{rowdata.title}}</td>         -->No need to make {{rowdata.weekly}}

</tr>

components.ts
--------------

getTableData(): void {
this._Service.getData()
    .subscribe(
res => {
this.TableData =  res;
this.TableRows = res.rows;
}
)
}

getclass(color){
if(color.weekly == 1){
return true;
}
}


service.ts
-----------

getData(): Observable<any> {
        return this._http.get('./app/systemMain/data.json')
                         .map(response => response.json())

    }

NG2- Model Change in Selection - Drop down box

NG2- Model Change in Selection - Drop down box:
-----------------------------------------------

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


//our root app component
import {Component, Directive, Output, EventEmitter, Input, SimpleChange} from 'angular2/core'
import {Observable} from 'rxjs/Observable';
import {Observer} from 'rxjs/Observer';
//import 'rxjs/Rx';


@Component({
    selector: 'my-app',
    template: `
    <h1>Hello</h1>
<select class="form-control" [(ngModel)]="selectedPrototypeSelector" (ngModelChange)="onPrototypeChange()">
   <option *ngFor="let p of prototypes" [ngValue]="p">
         {{ p.id }}
   </option>
</select>
<div>selected: {{selectedPrototypeSelector.id}}</div>
    `,
})
export class AppComponent {
  selectedPrototypeSelector;
  prototypes = [{id: 'a'}, {id: 'b'}, {id: 'c'}];
 
  constructor() {
    this.selectedPrototypeSelector = this.prototypes[1];
  }
 
  onPrototypeChange() {
    console.debug(this.selectedPrototypeSelector);
  }
}

CSS3- Transition- Left Menu Slide on Mouse Over

<html>
<head>
<style>

.slide{
 -webkit-transition:1s;
 border:1px solid red;
 float:right;
 position:relative;
 left:-50px;

}

.slide:hover{
margin-right:100px;

}

</style>
</head>
<body>

<div class="slide">
<ul>
<li>list1</li>
<li>list2</li>
<li>list3</li>
<li>list4</li>
<li>list5</li>
</ul>
</div>
</body>
</html>

HTML5- colored Checkbox - customize Design

<!DOCTYPE html>
<html>

  <head>
  <style>
  input[type="checkbox"] {
  display: none;
}

input[type="checkbox"] + label:before {
  border: 1px solid #7f83a2;
  content: "\00a0";
  display: inline-block;
  font: 16px/1em sans-serif;
  height: 16px;
  margin: 0 .25em 0 0;
  padding: 0;
  vertical-align: top;
  width: 16px;
}
input[type="checkbox"]:checked + label:before {
  background: green;
  color: white;
  content: "\2713";
  text-align: center;
}
  </style>
   
  </head>

  <body>
    <h1>Hello Plunker!</h1>
   
    <div class="content">
  <div class="box">
    <p>
      <input type="checkbox" id="c1" name="cb">
      <label for="c1">Option 01</label>
    </p>
    <p>
      <input type="checkbox" id="c2" name="cb">
      <label for="c2">Option 02</label>
    </p>
    <p>
      <input type="checkbox" id="c3" name="cb">
      <label for="c3">Option 03</label>
    </p>
  </div>
</div>

  </body>

</html>

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

bootstrap - Collapsesable code snippet

Bootstrap Collapse

<script src="https://code.jquery.com/jquery-3.1.1.min.js" ></script>


<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" >
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" ></script>
<style>


 <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="false" aria-controls="collapseOne">
          Collapsible Group Item #1
        </a>
         <div id="collapseOne" class="collapse out" role="tabpanel" aria-labelledby="headingOne">
      <div class="card-block">
       list view
      </div>
    </div>

Angular JS1 - Disable submit button until form is valid

Disable submit button when form invalid with AngularJS

To void this, you just need to handle $pending state of the form:

<form name="myForm">
  <input name="myText" type="text" ng-model="mytext" required />
  <button ng-disabled="myForm.$invalid || myForm.$pending">Save</button>
</form>