Wednesday 29 November 2017

ng switch in Angular

AngularngSwitch

Let us check how ngSwitch works in Angular. Basically it is almost similar to Angular js 1 except some syntax changes. Let us check how it is in Angular js 1 first.

ng-switch in Angular js 1



$scope.data = data; // json or backend data



<div ng-switch="data.status">
 
 <span ng-switch-when="C">Initializing</span>
 
 <span ng-switch-when="J">Loading</span>
 
 <span ng-switch-when="R">Creating</span>
 
 <span ng-switch-when="D">Success</span>
 
 <span ng-switch-when="P">Failed</span>

</div>


Now let us check how it is in Angular 4.

ngSwitch in Angular 4



this.data = data; // json or backend data



<div [ngSwitch]="data.status">
 
 <span *ngSwitchCase="'C'">Initializing</span>
 
 <span *ngSwitchCase="'J'">Loading</span>
 
 <span *ngSwitchCase="'R'">Creating</span>
 
 <span *ngSwitchCase="'D'">Success</span>
 
 <span *ngSwitchCase="'P'">Failed</span>
 
 <span *ngSwitchDefault>Error</span>

</div>

In this article we have discussed about using ngSwitch in Angular.

AngularngSwitch

Related Info

1. ng if in Angular 4.

2. ng if in Angular 2.

3. ng repeat in Angular.

4. ng click in Angular.

ng if in Angular 4/5

Angular 4/5ng if

Angular 4+ has updated there ng if capabilities, now it is more developer friendly. You can write if, else and then in html directly. Angular 2 ng if and Angular js 1 ng-if are almost same except some syntax changes. Let us check how it is in Angular 4 with some examples.

Angular 2 ng if




<div *ngIf="showSelected">
  <p>Condition Passed!</p>
</div>

<div *ngIf="!showSelected">
  <p>Condition Failed!</p>
</div>


Angular 4/5 ng if




<div *ngIf="showSelected; else hideSelected">
  <p>Condition Passed!</p>
</div>

<ng-template #hideSelected>
  <p>Condition Failed!</p>
</ng-template>


Let us check with another example



<div *ngIf="showSelected; then showTemplate else hideTemplate"></div>

<ng-template #showTemplate>
  <p>Condition Passed!</p>
</ng-template>

<ng-template #hideTemplate>
  <p>Condition Failed!</p>
</ng-template>


You can handle many scenarios like this in html itself and it is one of the great advantage of Angular 4. Let us check with one more scenario for showing loading message. This will be helpful as we need to show loading message for most of the dynamic data which is getting from backend.



<div *ngIf="dataFromServer; else loadingBar">
  <p>{{dataFromServer}}</p>
</div>

<ng-template #loadingBar>
  <p>Loading</p>
</ng-template>


Here loading message will be shown unless dataFromServer has got some values. Let me share component code as well, here I am setting the flag as true or false.

Component


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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  showSelected: boolean;
  dataFromServer: string;

  constructor() {
    this.showSelected = true;
    this.dataFromServer = 'Hello';

  }
}

In this article we have discussed about Angular 4 ng if with many examples.

Angular 4/5ng if

Related Info

1. Http calls in Angular with simple examples.

2. Set header for http request in Angular

3. Angular client side pagination.

4. Angular show more/less pagination

Tuesday 28 November 2017

Set header for http request in Angular

Angular 4HeaderCustom headerAngular 4.3.1

In this article we will be discussing about passing headers for http request. Most of the applications will be passing some ticket for all http calls, this will help to improve the security of the application. Let us check with an example how we can pass a header for http request. I have explained the same using angular js 1 concept as well , if you want to compare both implementations you can check this link.

If you are using angular version 4.3 or above check this link:- Set header for http request in angular 5(4.3+)

Pass header for single http request.


I have used Angular 4.0.0 version to do this. Check below code for more info.


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


@Injectable()
export class userDataService {
    _url: string;
    constructor(private http: Http) { }

    getUserslist(): Observable<any[]> {

        this._url = 'your api';

        const headers = new Headers();
        headers.set('authentication', 'auth ticket');
        const options = new RequestOptions({ headers: headers });

        return this.http.get(this._url, options)
            .map(this.handleData)
            .catch(this.handleError);
    }
}

You can append more values as well like below example.


const headers = new Headers();
headers.set('authentication', 'auth ticket');
headers.append('authentication1', 'auth ticket1'); 

We are done, invoke the API and check network tab. If you want to know more about http call and different methods check this link.

Pass headers for all http headers using Angular interceptor.


We have already discussed about how we can pass headers to a single http request. Now let us check with another example, where we can pass headers for all https calls using Angular interceptor concept. Unfortunately this required Angular 4.3.1 version. Update your angular version to try this. Create a ts file and name it as httpInterceptorClass (any name).


import { Injectable } from '@angular/core';
import { HttpInterceptor,HttpRequest,HttpHandler,HttpEvent} from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
 
@Injectable()
export class httpInterceptorClass implements HttpInterceptor {
  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const customHeaderRequest = request.clone({
      headers: request.headers.set('authTicket', '#112222')
    });
 return next.handle(customHeaderRequest);
  }
}

We are done.

Since you have already upgraded Angular version, try below code for setting headers for single http header as well.


const headers = new HttpHeaders()
      .set('authTicket', '#112222');



In this article we have discussed about passing header for all http calls and also for single http request as well.

Angular 4HeaderCustom headerAngular 4.3.1

Related Info

1. Http calls in Angular with simple examples.

2. Disable submit button until all mandatory fields are filled - Angular

3. Angular client side pagination.

4. Angular show more/less pagination

Monday 27 November 2017

Http calls in Angular with simple examples.

Angular 4Http

In this article we will be discussing about how to do an http calls in angular 2+. We already know about http calls in Angular js 1. It is entirely different in Angular 2, let us check those with very simple example. I will be using Observable concept for this.

Http get with Observable concept


Let us create a simple component first, and we need to import/inject required things.

Component


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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  
  constructor(private userService:userDataService) {}
  
  triggerGetApi()
  {
    this.userService.getUserslist().subscribe(
      response => this.handleResponse(response), 
      error => this.handleError(error) 
    )
  }
  handleResponse(response:any)
  {
    console.log(response);
  }
  handleError(error:string){
    console.log(error);
  }
}

Here userDataService is nothing but our service file, where we will be making our http calls. handleResponse method will be receiving success response from http results and error in handleError method. Now let me share our userDataService file.

Service file


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


@Injectable()
export class userDataService {
    _url: string;
    constructor(private http: Http) { }

    getUserslist(): Observable<any[]> {
        this._url = 'your api';

        return this.http.get(this._url)
            .map(this.handleData)
            .catch(this.handleError);
    }
    private handleData(res: Response) {
        let data = res.json();
        return data;
    }
    private handleError(error: Response | any) {
        return Observable.throw('API failed');
    }
}

And we are done. I think above code is self-explanatory. Don’t forget to import/inject above mentioned dependencies. You can test this by replacing the url with your ones. You can also get many sample API for testing. I will share the module code as well for better understanding.

Module


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import {userDataService} from './userDataService';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpModule
  ],
  providers: [userDataService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Http POST with Observable concept


Let us check how we can do a post call using Angular. It is almost same except we need to pass the data. Check below component code first

Component


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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {

  item: {};
  constructor(private userService: userDataService) { }

  triggerPostApi() {
    this.item = {
      name: 'Angular',
      type: 'Framework',
      parent: 'Javascript'
    }
    this.userService.sendUserData(this.item).subscribe(
      response => this.handleResponse(response),
      error => this.handleError(error)
    )
  }
  handleResponse(response: any) {
    console.log(response);
  }
  handleError(error: string) {
    console.log(error);
  }
}

There is no difference here except we need to pass the data. Now let us check the service file code.

Service file


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


@Injectable()
export class userDataService {
    _url: string;
    constructor(private http: Http) { }

    sendUserData(item: {}): Observable<{}> {

        this._url = 'your api';

        return this.http.post(this._url, item)
            .map(this.handleData)
            .catch(this.handleError);
    }

    private handleData(res: Response) {
        let data = res.json();
        return data;
    }
    private handleError(error: Response | any) {
        return Observable.throw('API failed');
    }
}

We are done. If you want to pass headers also along with this add below code as well.


import { Headers, RequestOptions } from '@angular/http';
//add headers and request options


sendUserData(item: {}): Observable<{}> {

 this._url = 'your api';

 let headers = new Headers({ 'Content-Type': 'application/json' });
 let options = new RequestOptions({ headers: headers });

 return this.http.post(this._url, item, options)
  .map(this.handleData)
  .catch(this.handleError);
}

Don’t forget to add the dependencies mentioned above.

In the error block we have passed a hardcoded string in the above example. You can pass entire error block or particular message from api as well.


return Observable.throw(error.message | error);

Http Delete with Observable concept


It is almost similar to post method, check below component and service file code.

Component


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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  id: Number;
  constructor(private userService: userDataService) {}
  
  triggerDeleteApi() {
    this.id = 12;
    this.userService.deleteUser(this.id).subscribe(
      response => this.handleResponse(response),
      error => this.handleError(error)
    )
  }
  handleResponse(response: any) {
    console.log(response);
  }
  handleError(error: string) {
    console.log(error);
  }

}

Service file


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


@Injectable()
export class userDataService {
    _url: string;
    constructor(private http: Http) { }

    deleteUser(id: Number): Observable<Number> {
        this._url = 'your api' + id;

        return this.http.delete(this._url)
            .map(this.handleData)
            .catch(this.handleError);
    }

    private handleData(res: Response) {
        let data = res.json();
        return data;
    }
    private handleError(error: Response | any) {
        return Observable.throw('API failed');
    }
}

Retry if API is failed.


This is one of the good feature in Angular 2+ (using RxJS). It will reinitiate the API call if it is failed. You can simply specify how many times this need to check. Suppose you mentioned Retry(2), it will try to call two times if API failed.

Retry()


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


@Injectable()
export class userDataService {
    _url: string;
    constructor(private http: Http) { }

    getUserslist(): Observable<any[]> {
        
        this._url = 'your api';

        return this.http.get(this._url)
            .retry(2)//it will retry for two times if API failed
            .map(this.handleData)
            .catch(this.handleError);
    }
 private handleData(res: Response) {
        let data = res.json();
        return data;
    }
    private handleError(error: Response | any) {
        return Observable.throw('API failed');
    }
} 

Angular 4Http

Related Info

1. How to show a date is today or yesterday or last week etc using pipe - Angular

2. Disable submit button until all mandatory fields are filled - Angular

3. Angular client side pagination.

4. Angular show more/less pagination

Tuesday 21 November 2017

Angular simple sort.

Here I will be discussing about doing a simple sort using Angular and JavaScript. Let us create a simple table with an option to select sortable fields.

Component code


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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  item : any[];
  keys : any[];
  
  constructor(){
    this.item = [
        {firstName :'Prashobh',lastName : 'PS',age:28},
        {firstName :'Abraham',lastName : 'A',age:38},
        {firstName :'Zian',lastName : 'Z',age:16},
        {firstName :'Catherin',lastName : 'CZ',age:24},
      ]
     this.keys = Object.keys(this.item[0]); 
  }
}

Html


<select class="selectClass" [(ngModel)]="selected" (change)="onChange($event.target.value)">
 <option [ngValue]="no-value" disabled selected>Select</option>
 <option *ngFor="let k of keys">{{k}}</option>
</select>


<table class="table">
 <thead>
   <tr>
 <th scope="col">First Name</th>
 <th scope="col">Last Name</th>
 <th scope="col">Age</th>
   </tr>
  </thead>
  <tbody>
  <tr *ngFor="let l of item">
 <td>{{l.firstName}}</td>
 <td>{{l.lastName}}</td>
 <td>{{l.age}}</td>
  </tr>
 </tbody>
</table>



We have created a simple table along with a select box to select sortable fields. And below is our simple sort method.


onChange(value: string) {
 this.item.sort(function (a, b) {
  if (a[value] < b[value]) {
 return -1;
  }
  if (a[value] > b[value]) {
 return 1;
  }
  return 0;
 });
}

We are done. Select the field in select box to sort the table.

Here we have discussed about implementing a simple sort using Angular and JavaScript.

Related Info

1. How to show a date is today or yesterday or last week etc using pipe - Angular

2. Disable submit button until all mandatory fields are filled - Angular

3. Angular client side pagination.

4. Angular show more/less pagination

Monday 20 November 2017

JavaScript Regex list

JavaScript regex will help you to do client side validation very easily. In this article I will be sharing various regex examples. Below list contains regex with various conditions. I will be updating this list frequently with new regex condition. It will help everyone rather than spending time for creating new one, just open the link and select appropriate ones.

You can check the regex very easily using some of these site - regexpal.com, regex101.com. Or simply open the console and write like below,


var regex  = 'yourregex pattern';
regex.exec('text to be tested')

If it returns null means validation conditions are not met, else it is success. You can use any of these to test below regex before using it. You can use this by simply putting along with html input. For example


// html
<input type="text" required pattern="/^[A-Za-z]\w*$/"> 

//angular
<input type="text" required ng-pattern="/^[A-Za-z]\w*$/"> 

//or inside javascript file
var regex = "/^[A-Za-z]\w*$/";
var _text = "validateMe";

if(regex.exec(_text) != null){
 //success
}

JavaScript regex list.


Description Regex
• Only allows alphanumeric.
/^[a-z0-9]+$/i
• Minimum 6 and maximum 20 characters.
• Must have at least one number
/^(?=.*\d).{6,20}$/
• Alphanumeric.
• Allow some special characters (#, %, *, .)
/^[a-zA-Z0-9 #/()\$%/{}/&*\[.]*$/
• Only allows number.
• No decimal values
/^\d+$/
• Alphanumeric.
• No special charactors but allow underscore
• Should not start with a number or underscore.
/^[A-Za-z]\w*$/
• Minimum ten characters .
• At least one letter
• At least one number.
/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{10,}$/
• Minimum ten characters .
• At least one letter
• At least one number.
• At least one special character.
/^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@$!%*#?&])[A-Za-z\d$@$!%*#?&]{10,}$/
• Minimum ten characters .
• At least one uppercase letter
• At least one lowercase letter.
• At least one number
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{10,}$/
• Minimum ten characters.
• At least one uppercase letter
• At least one lowercase letter.
• At least one number
• At least one special character
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{10,}/
• Minimum ten and maximum 20 characters.
• At least one uppercase letter
• At least one lowercase letter.
• At least one number
• At least one special character
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{10,20}/
• Url validation (http://www.angulartutorial.net). ^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$
• Minimum ten and maximum 20 characters.
• At least one uppercase letter
• At least one lowercase letter.
• At least one number
• At least one (any)special character or underscore
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[_\W]).{12,20}$/

In this article we have discussed about JavaScript regex and also added examples for regex with various conditions. I will be updating this list frequently.

Friday 3 November 2017

Multiselect checkbox dropdown component using Angular

Here I am going to explain about creating a simple multi select checkbox dropdown component using angular. This component can reuse by adding anywhere in the application. Let check with working example.


<multi-selector-dropdown
 [list]="list"
 (shareCheckedList)="shareCheckedList($event)" 
 (shareIndividualCheckedList)="shareIndividualCheckedList($event)">
</multi-selector-dropdown>

Above one is our component representation. Here list is nothing but the data that required to show in the drop down. shareCheckedList will provide the checked list information in the parent controller and shareIndividualCheckedList will provide individual status of selected item.

Let us create a component there we will be adding our drop down component.


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

@Component({
  selector: 'app-root',
  template: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
 
  list : any[];
  
  constructor(){
    this.list = 
      [
        {name :'India',checked : false},
        {name :'US',checked : false},
        {name :'China',checked : false},
        {name :'France',checked : false}
      ]
  }
}

and html


<multi-selector-dropdown
 [list]="list"
 (shareCheckedList)="shareCheckedList($event)" 
 (shareIndividualCheckedList)="shareIndividualCheckedList($event)">
</multi-selector-dropdown>

Above list will be using for creating our drop down. Now check multi drop down checkbox component.

Multi drop down checkbox component


import {Component,Input,Output,EventEmitter} from '@angular/core';

@Component({
    selector :'multi-selector-dropdown',
    templateUrl :'./multiSelectDropdown.html',
    styleUrls : ['./app.component.css']
})

export class MultiSelectDropdown{
    @Input() list:any[]; 
    
    @Output() shareCheckedList = new EventEmitter();
    @Output() shareIndividualCheckedList = new EventEmitter();
    
    
    checkedList : any[];
    currentSelected : {};
    
    constructor(){
        this.checkedList = [];
    }
    getSelectedValue(status:Boolean,value:String){
        if(status){
          this.checkedList.push(value);  
        }else{
            var index = this.checkedList.indexOf(value);
            this.checkedList.splice(index,1);
        }
        
        this.currentSelected = {checked : status,name:value};

        //share checked list
        this.shareCheckedlist();
        
        //share individual selected item
        this.shareIndividualStatus();
    }
    shareCheckedlist(){
         this.shareCheckedList.emit(this.checkedList);
    }
    shareIndividualStatus(){
        this.shareIndividualCheckedList.emit(this.currentSelected);
    }
}

./multiSelectDropdown.html


<div>
    <h3>Multi select dropdown</h3>
    <div (mouseleave)="showDropDown = false">
        <button class="drop-toggle btn flat" (click)="showDropDown=!showDropDown">
            <span *ngIf="checkedList.length<=0">Select</span>
            <span *ngIf="checkedList.length>0">{{checkedList.join(', ')}}</span>
            <i class="fa fa-angle-down"></i>
        </button>
        <div class="drop-show" *ngIf="showDropDown">
            <label *ngFor="let a of list">
                <input type="checkbox" [(ngModel)]="a.checked" 
                    (change)="getSelectedValue(a.checked,a.name)" />
                <span>{{a.name}}</span>
            </label>
        </div>
    </div>
</div>

Here we have used EventEmitter, @input and @output method to share and receive the data. You can read this article for know more about sharing data between components.

Updated parent component


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

@Component({
  selector: 'app-root',
  template: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
 
  list : any[];
  
  constructor(){
    this.list = 
      [
        {name :'India',checked : false},
        {name :'US',checked : false},
        {name :'China',checked : false},
        {name :'France',checked : false}
      ]
  }
  shareCheckedList(item:any[]){
    console.log(item);
  }
  shareIndividualCheckedList(item:{}){
    console.log(item);
  }
}

We just updated our parent component to receive the data from drop down component.

In case anyone interested in css for the above drop down, here it is,

CSS


/***
    css for multi select drop down
**/
.drop-toggle{
    background-color: #fff;
    border: none;
    padding: 5px 10px;
    border-radius: 4px;
    cursor: pointer;
    cursor: hand;
    border: 1px solid #ccc;
    width: 233px;
    text-align: left;
}
.drop-toggle i{
    float:right;
}
.drop-show {
    padding: 4px;
    width: 222px;
    background-color: #FFF;
    border: 1px solid #BABABA;
    position: absolute;
    z-index: 100;
    -webkit-box-shadow: 0 6px 10px rgba(0,0,0,.15);
    -moz-box-shadow: 0 6px 10px rgba(0,0,0,.15);
    box-shadow: 0 6px 10px rgba(0,0,0,.15);
    margin-left: 1px;
}
.drop-show label{
    display:block;
    font-size:15px;
    cursor: pointer;
}
.drop-show label input{
    vertical-align: top;
}
.drop-show label span{
    display:inline-block;
}

Demo

We are done, don’t forget to import the dependencies in your module. In this article we have discussed about creating a multi select checkbox drop down component using Angular, which can reuse any where in your module.

Related Info

1. How to show a date is today or yesterday or last week etc using pipe - Angular

2. Disable submit button until all mandatory fields are filled - Angular

3. Angular client side pagination.

4. Angular show more/less pagination