Friday, 20 January 2017

Datepicker In Angular 2

To use the datepicker in the angular 2 application use ng2-bootstrap
include ng2-bootstrap and moment in your package.json and hit npm install to install both in the node_modules
include datepicker module in your module file. The app.module.ts file will be,
import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { DatepickerModule } from 'ng2-bootstrap/ng2-bootstrap';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { DatepickerComponent } from './datepicker.component';

@NgModule({
  imports:      [ BrowserModule, DatepickerModule],
  declarations: [ AppComponent, DatepickerComponent ],
  bootstrap:    [ AppComponent ]
})

export class AppModule { }
    
Create the text box in html and write the functionality in the ts file like
<div class="container">
    <div class="col-md-6">
        <label for="datepicker" class="text-primary">Date Picker</label>
        <div class="input-group date-picker">
            <input type="text" class="form-control" name="datpicker" id="datpicker" placeholder="Date Picker" [(ngModel)]="datePickerValue" (focus)="showDatePicker()" readonly>
            <span class="input-group-addon" (focus)="showDatePicker()"><span class="glyphicon glyphicon-calendar" aria-hidden="true"></span></span>
        </div>
        <div class="dp-popup" *ngIf="isDatePickerShown">
            <datepicker [(ngModel)]="datePickerDate" [showWeeks]="false" [maxDate]="today" [ngModelOptions]="{standalone: true}" (selectionDone)="dateSelected($event)"></datepicker>
        </div>   
    </div>
</div>
    
import { Component, OnInit, ViewChild } from '@angular/core';
import { DatepickerModule } from 'ng2-bootstrap/ng2-bootstrap';
import * as moment from 'moment';

@Component({
    selector: 'datepicker-component',
    templateUrl: 'datepicker.component.html',
    host: {
        '(document:click)': 'handleClick($event)'
    },
})

export class DatepickerComponent {
    
    isDatePickerShown:boolean = false;
    datePickerDate;
    datePickerValue;
    today:Date = new Date();

    constructor() {
        
    }

    showDatePicker(){
         this.isDatePickerShown = true;
     }

     hideDatePicker(){
         this.isDatePickerShown = false;
     }

     dateSelected(event){
         this.datePickerValue = moment(event).format("YYYY-MM-DD");
         this.hideDatePicker();
     }

     handleClick(event){
         if(!(event.target.closest('datepicker') != null || event.target.closest('.btn') != null || event.target.closest('.date-picke') != null)){
             this.hideDatePicker();
         }
     }

}
    

Bootstrap Modal in Angular 2

To use the bootstrap modal in the angular 2 application use ng2-bootstrap
include ng2-bootstrap and moment in your package.json and hit npm install to install both in the node_modules
include modal module in your module file. The app.module.ts file will be,
import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ModalModule } from 'ng2-bootstrap/ng2-bootstrap';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { BootstrapModalComponent } from './bootstrap-modal.component';

@NgModule({
  imports:      [ BrowserModule, ModalModule],
  declarations: [ AppComponent, BootstrapModalComponent ],
  bootstrap:    [ AppComponent ]
})

export class AppModule { }
    
Write the bootstrap modal in html and write the functionality in the ts file like
<div class="container">
        <button type="button" class="btn btn-default" (click)="showModal()">Open</button>
    </div>
    <div bsModal #bootstrapModal="bs-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="bootstrapModal"
    aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" aria-label="Close" (click)="closeModal()">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title">Bootstrap modal</h4>
            </div>
            <div class="modal-body">
                <p>This is bootstrap modal</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" (click)="closeModal()">Close</button>
            </div>
        </div>
    </div>
</div>
    
import { Component, OnInit, ViewChild } from '@angular/core';
import { ModalDirective } from 'ng2-bootstrap/ng2-bootstrap';

@Component({
    selector: 'bootstrap-modal',
    templateUrl: 'bootstrap-modal.component.html'
})

export class BootstrapModalComponent {
    
    @ViewChild('bootstrapModal') public bootstrapModal:ModalDirective;

    constructor() {        
    }

    showModal(){
        this.bootstrapModal.show();
    }

    closeModal(){
        this.bootstrapModal.hide();
    }

}
    

Thursday, 19 January 2017

Using forge-js in angular 2 for calculating sha256

To use forge-js in angular 2 application for using cryptographic function like sha clone the repository from the git and build the files and include the forge.all.js file in your index.html file
Since the forge-js is not written in typescript and not having the d.ts file. We have to declare the forge and use the functions inside that.
To calculate the sha256 enter the code like.
declare var forge:any;

export class Common{
    getSha256String(value){
      var md = forge.md.sha256.create();
      md.update(value);
      return md.digest().toHex();
    },
}
Now simply call the method getSha256String with the value to get the encrypted value.

Monday, 31 October 2016

Change Password Form In Angular 2

Angular 2 doesnt having validation for checking two fields having equal values, for that we need to create custom validation.
Lets create a change password form to demonstrate the custom validation for matching new password and confirm new password.
<div class="row">
    <div class="col-md-offset-3 col-md-6">
        <div class="panel panel-default">
            <div class="panel-body">
                <h2 class="text-center">Change Password</h2>
                <form [formGroup]="changePasswordForm" (ngSubmit)="changePassword(changePasswordForm.value)">
                    <div class="form-group" [ngClass]="{'has-error':!changePasswordForm.controls['old_password'].valid && changePasswordForm.controls['old_password'].touched}">
                        <label for="old_password">Old Password</label>
                        <input type="password" name="old_password" class="form-control" id="oldPassword" placeholder="Old Password" [formControl]="changePasswordForm.controls['old_password']" />
                        <small *ngIf="changePasswordForm.controls['old_password'].hasError('required') && changePasswordForm.controls['old_password'].touched" class="text-danger">Old Password Required</small>
                    </div>
                    <div class="form-group" [ngClass]="{'has-error':!changePasswordForm.controls['new_password'].valid && changePasswordForm.controls['new_password'].touched}">
                        <label for="new_password">New Password</label>
                        <input type="password" name="new_password" class="form-control" id="newPassword" placeholder="New Password" [formControl]="changePasswordForm.controls['new_password']" />
                        <small *ngIf="changePasswordForm.controls['new_password'].hasError('required') && changePasswordForm.controls['new_password'].touched" class="text-danger">New Password Required</small>
                    </div>
                    <div class="form-group" [ngClass]="{'has-error':!changePasswordForm.controls['confirm_new_password'].valid && changePasswordForm.controls['confirm_new_password'].touched}">
                        <label for="confirm_new_password">Confirm New Password</label>
                        <input type="password" name="confirm_new_password" class="form-control" id="newPassword" placeholder="Confirm New Password" [formControl]="changePasswordForm.controls['confirm_new_password']" />
                        <small *ngIf="changePasswordForm.controls['confirm_new_password'].hasError('required') && changePasswordForm.controls['c:onfirm_new_password'].touched" class="text-danger">Confirm New Required</small>
                        <small *ngIf="changePasswordForm.controls['confirm_new_password'].hasError('passwordMatch') && changePasswordForm.controls['confirm_new_password'].touched" class="text-danger">Password mismatch</small>
                    </div>
                    <div class="form-group text-center">
                        <button type="submit" class="btn btn-default" [disabled]="!changePasswordForm.valid">Change Password</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
Now, lets create a ts component for this
    import { Component } from '@angular/core';
    import { FormGroup, FormBuilder, FormControl, Validators, AbstractControl } from '@angular/forms';
    
    @Component({
      selector: 'change-password',
      templateUrl:'change-password.component.html',
      providers: [ UserService ]
    })
    
    export class ChangePasswordComponent {
    
        changePasswordForm:FormGroup;

        constructor(fb: FormBuilder){
            this.changePasswordForm = fb.group({
                'old_password': [null, Validators.required],
                'new_password': [null, Validators.required],
                'confirm_new_password': [null, [Validators.required, this.passwordMatch]] 
            });
        }
    
        passwordMatch(control: AbstractControl){
            let paswd = control.root.get('new_password');
            if(paswd && control.value != paswd.value){
             return {
                 passwordMatch: false
             };   
            }
            return null;
        }
    
        changePassword(value){
            if(this.changePasswordForm.valid){
                console.log("Change password form valid");
            }
        }
    
    }
    
Thats it, now register this component in the app module and use the selector <change-password></change-password> to see the change password form

Simple Login Form With Validation in Angular 2

Angular 2 having the form builder to build the login form with the validation, Here we see a simple login form with the validation.
Lets first create a html component with the user name and password form
<div class="row">
    <div class="col-md-offset-4 col-md-4">
        <div class="panel panel-default">
            <div class="panel-body">
                <h2 class="text-center text-muted">Login</h2>
                <form [formGroup]="loginForm" (ngSubmit)="login(loginForm.value)">
                    <div class="form-group" [ngClass]="{'has-error':!loginForm.controls['user_name'].valid && loginForm.controls['user_name'].touched}">
                        <label for="username">User Name</label>
                        <input type="text" name="user_name" class="form-control" id="username" placeholder="User Name" [formControl]="loginForm.controls['user_name']" />
                        <small *ngIf="loginForm.controls['user_name'].hasError('required') && loginForm.controls['user_name'].touched" class="text-danger">Username Required</small>
                    </div>
                    <div class="form-group" [ngClass]="{'has-error':!loginForm.controls['password'].valid && loginForm.controls['password'].touched}">
                        <label for="password">Password</label>
                        <input type="password" name="username" class="form-control" id="password" placeholder="Password" [formControl]="loginForm.controls['password']" />
                        <small *ngIf="loginForm.controls['password'].hasError('required') && loginForm.controls['password'].touched" class="text-danger">Password Required</small>
                    </div>
                    <div class="form-group text-center">
                        <button type="submit" class="btn btn-default" [disabled]="!loginForm.valid">Login</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
The html component is created, now lets create the ts component for this form.
import { Component } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'login-section',
  templateUrl:'login.component.html'
})

export class LoginComponent {
    loginForm: FormGroup;

    constructor(fb: FormBuilder){
        this.loginForm = fb.group({
            'user_name': [null, Validators.required],
            'password': [null, Validators.required]
        });
    }


    login(value){
        if(this.loginForm.valid){
           console.log("Login form valid");
        }        
    }
    
 }
Thats it, we have created the login form with validation, now register this component in the app.module and use the selector <login-section></login-section> to see the login form.

Monday, 24 October 2016

Apply where condition if input exists in Laravel Eloquent ORM

If you want to apply multiple where condition based on whether particular inputs are present in laravel Eloquent ORM, we can use the array applied within the where.

Consider we are having the Movie table with its fields id, name, genre, year. we want to gets all movies list with or without genre and year.

public function getMovies($input) {
    $condition = array();
    if(!empty($input['genre'])){
        array_push($condition, ['genre', $input['genre']]);
    }
    if(!empty($input['year'])){
        array_push($condition, ['year', $input['year']]);
    }
    
    $result = Movie::where($condition)->get();
    return $result;
}

Thursday, 20 October 2016

Checking Internet connection in web page using offline js

To check internet connection is active or not in the web page we can use the Offline.js plugin

Clone the git repository and include the offline.min.js file and any theme css file like offline-theme-slide.css with language css file offline-language-english.css

By default it will ping favicon.ico file in the server, we can customize it to any request

Offline.options = {checks: {image: {url: 'path/to/favicon/image'}, active: 'image'}}

To check the current status of the connection

Offline.check()

To check the current state of the connection 'up' or 'down'

Offline.state

To set event listener once connection is up

Offline.on('up', function(){
    console.log('Connection is up.');
});

To set event listener once connection is down

Offline.on('down', function(){
    console.log('Connection is down.');
});