Angular

                                                                                                                    << BACK

Angular Website Learning URL is :
-> https://cli.angular.io/
-> https://angular.io/docs/ts/latest/api
-> https://github.com/angular/angular-cli
-> https://update.angular.io/
-> https://coursetro.com/courses/19/Learn-Angular-5-from-Scratch---Angular-5-Tutorial


For VisualStudio Download URL is : https://code.visualstudio.com/Download
For Node Download URL is : https://nodejs.org/en/download/


*Other Command for angular cli
> npm install -g typescript
> npm install decimal.js --save
> npm install --save @types/decimal.js

*install of rxjs command
> npm install rxjs
> npm install --save rxjs-compat
restart server

*update npm then command is
> npm i


*app current behavior to check command
> ng build --prod --verbose 

---------------------------------------------------------------------------------------------
 1) Installation :
open cmd in window
check node install or not to type command > node -v  -> output : (v8.11.4)
then check npm version type to command line > npm -v -> output : (5.6.0)
after install angular cli command is > npm install -g @angular/cli
then type commond ng -v to run angular cli
then creat new project commond with roution and style is
> ng new projectName --style=scss --routing
and normal command is :
> ng new project-name

start to project then
then go to directory of project name > cd project-name
then start service > ng serve
in case of change port to use command > ng serve --host 0.0.0.0 --port 4201
---------------------------------------------------------------------------------------------
2) Component :
In project src folder -> app folder
in app folder app.component is parent component of project
and other than app.component all other component is child component
If create new component then use command
> ng g component component-name
or
> ng g c component-name
---------------------------------------------------------------------------------------------
3) Include Component:
include page in main component then go to child component ts file copy the @Component>selector name like app-firstpage and past to main component name app.component.html file like <app-firstpage></app-firstpage>
---------------------------------------------------------------------------------------------
4) Routing:
-> routing section => in app.module.ts file first import router library and also write router code in imports section
import { RouterModule, Router, Routes, ActivatedRoute } from '@angular/router';
imports: [
    RouterModule.forRoot([
        {
            path: '',
            component : LoginComponent
        },
        {
            path: 'dashboard',
            component : DashboardComponent
        }
    ])
]

Note : 
path : '' is default router of website 

-> in app.component.html  page write a link tag like <a routerLink="/secondpage">Second Page</a> and show routing data in app.component use tag like <router-outlet></router-outlet>
---------------------------------------------------------------------------------------------
5) Data Binding:
-> write title or obj or array in component.ts file under export class and in html write code in {{title}}
e.g : in component.ts like : title = 'project-name-first';
component.html page is {{title}}
---------------------------------------------------------------------------------------------
6) Variable Declared:
in component.ts file first declare variable then call this variable
e.g.
queryString = ""; //string
customerLoader = false; //Boolean value
customerList: any[]; // array
selectedFileBase: {}; //json
p: number = 1; // number
selectedFiles: FileList; //file
currentFileUpload: File; //file 
---------------------------------------------------------------------------------------------
7) Boolean expressions true or false:
-> component.ts file
 employeeLoader = false;
-> component.html file
 <div class="loader" *ngIf="employeeLoader">
    <img class="img-responsive" src="assets/images/loading.gif" />
 </div>
---------------------------------------------------------------------------------------------
8) If Else Condition:

---------------------------------------------------------------------------------------------
9) Switch Condition:
---------------------------------------------------------------------------------------------
10) For Loop:
-> normal for loop
********************************************************
-> for loop with indexing
 ********************************************************
-> for loop with First value is true
 ********************************************************
-> for loop with Last value is true
 ********************************************************
-> for loop with Even Index value is true
 ********************************************************
-> for loop with Odd Index value is true
---------------------------------------------------------------------------------------------
11) single page application (add and update with angular validation With Loader):
app.module.ts file
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule,ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { RouterModule, Router, Routes, ActivatedRoute } from '@angular/router';
imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    HttpClientModule
]

component.ts file
import { HttpClient } from '@angular/common/http';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { ApiService } from './../api.service';

export class SinglepageComponent implements OnInit {
    employeeLoader = false;
    statusCode = "";
   
    //add form data to create array
    emplyeeManagementAddForm = new FormGroup({
        user_id             : new FormControl(""),
        employee_name         : new FormControl("",Validators.required),
        employee_email_id     : new FormControl("",Validators.required),
        mobile_number         : new FormControl("",Validators.required),
        dateofbirth_date     : new FormControl("",Validators.required),
        employee_gender     : new FormControl("",Validators.required),
        employee_marital     : new FormControl("",Validators.required),
        marital_date         : new FormControl(""),
        employee_education     : new FormControl("",Validators.required),
        work_experience     : new FormControl("",Validators.required),
        profile_pic         : new FormControl(""),
        saveProfilePicInput : new FormControl("",Validators.required),
        employee_address     : new FormControl("",Validators.required)
    });
   
    //add and update data to call function
    addEmployeeDetails = function(emplyeeManagementAddForm){
        if (($("#saveProfilePicInput").val() == '') || ($("#saveProfilePicInput").val() == undefined)) {
            $('#savePicErrorDiv').html("Please Upload Profile Picture 123.");
            return false;
        } else {
            $('#savePicErrorDiv').html("");
        }
        if($('#employee_marital').val() == 'Married'){
            if (($("#marital_date").val() == '') || ($("#marital_date").val() == undefined)) {
                $('#maritalDateErrorDiv').html("Please Select Marital Date.");
                return false;
            } else {
                $('#maritalDateErrorDiv').html("");
            }
        }
          let mySetItem = this.localSt.retrieve('user_id');
        this.employeeLoader = true;
        let sendEmployeeSaveData = {
              'method'                  : btoa('addEmployee'),
              'user_id'                : emplyeeManagementAddForm.user_id,
              'employee_name'          : emplyeeManagementAddForm.employee_name,
              'employee_email_id'      : emplyeeManagementAddForm.employee_email_id,
              'mobile_number'          : emplyeeManagementAddForm.mobile_number,
              'dateofbirth_date'      : new Date(emplyeeManagementAddForm.dateofbirth_date).toLocaleDateString('en-US'),
              'employee_gender'          : emplyeeManagementAddForm.employee_gender,
              'employee_marital'      : emplyeeManagementAddForm.employee_marital,
              'marital_date'          : new Date(emplyeeManagementAddForm.marital_date).toLocaleDateString('en-US'),
              'employee_education'      : emplyeeManagementAddForm.employee_education,
              'work_experience'          : emplyeeManagementAddForm.work_experience,
              'avatar'                  : emplyeeManagementAddForm.saveProfilePicInput,
              'employee_address'      : emplyeeManagementAddForm.employee_address,
              'login_user_id'           : mySetItem
        };
        console.log(sendEmployeeSaveData);
        this.apiService.checkDataToServerFunction(sendEmployeeSaveData)
        .subscribe(data => {
            console.log(data);
            if(data.is_success == '1'){
                this.statusCode = data.msg;
            } else if(data.is_success == '0'){
                this.statusCode = data.msg;
            }
            this.emplyeeManagementAddForm.reset();   
              this.employeeLoader = false;
            this.getAllEmployeeList();
        });
    }
 }

component.html file

<div class="loader" *ngIf="employeeLoader">
    <img class="img-responsive" src="assets/images/loading.gif" />
</div>

 <form autocomplete="off" name="emplyeeManagementAddForm" id="emplyeeManagementAddForm" [formGroup] = "emplyeeManagementAddForm" (ngSubmit)="addEmployeeDetails(emplyeeManagementAddForm.value)" >
    <div class="panel panel-flat panel-collapsed">
        <div class="panel-heading">
            <h5 class="panel-title">  Employee</h5>
            <div class="heading-elements addClickElements">
                <ul class="icons-list">
                  <li><a data-action="collapse" class="rotate-180"></a></li>
                </ul>
            </div>
        </div>

        <div class="panel-body">
            <div class="row">
                <div class="col-md-12 col-sm-12 col-xs-12 fullformArea">
                    <fieldset>
                        <input type="hidden" formControlName="user_id" name="user_id" id="user_id"  class="form-control" />
                        <div class="row">
                            <div class="col-md-3 formfieldbox">
                                <div class="form-group">
                                    <label>Employee Name</label>
                                    <input type="text" myCharacterOnly name="employee_nameformControlName="employee_name" placeholder="Enter Employee Name" class="form-control" />
                                    <span class="error-msg" *ngIf="emplyeeManagementAddForm.controls.employee_name.invalid && (emplyeeManagementAddForm.controls.employee_name.touched || emplyeeManagementAddForm.controls.employee_name.valid)">
                                        Please Enter Name.
                                    </span>
                                </div>
                            </div>
                            <div class="col-md-3 formfieldbox">
                                <div class="form-group">
                                    <label>Email </label>
                                    <input type="email" name="employee_email_id" formControlName="employee_email_id" placeholder="abc@ashoutnow.com" class="form-control" />
                                    <span class="error-msg" *ngIf="emplyeeManagementAddForm.controls.employee_email_id.invalid && (emplyeeManagementAddForm.controls.employee_email_id.touched || emplyeeManagementAddForm.controls.employee_email_id.valid)">
                                        Please Enter Email Id.
                                    </span>
                                </div>
                            </div>
                            <div class="col-md-3 formfieldbox">
                                <div class="form-group">
                                    <label>Mobile Number</label>
                                    <input type="text" myNumberOnly id="mobile_number" formControlName="mobile_number" name="mobile_number" minlength="10" maxlength="10" placeholder="9999999999" class="form-control" />
                                    <span class="error-msg" *ngIf="emplyeeManagementAddForm.controls.mobile_number.invalid && (emplyeeManagementAddForm.controls.mobile_number.touched || emplyeeManagementAddForm.controls.mobile_number.valid)">
                                        Please Enter Mobile Number.
                                    </span>
                                </div>
                            </div>
                            <div class="col-md-3 formfieldbox">
                                <div class="form-group">
                                    <label>Date of Birth</label>
                                    <div class="input-group selectMultiDates2">
                                       <span class="input-group-addon">
                                           <i class="glyphicon glyphicon-calendar"></i>
                                       </span>
                                       <input readonly="" bsDatepicker [bsConfig]="{ dateInputFormat: 'YYYY-MM-DD' }" [maxDate]="maxDate" class="form-control selectdate" name="dateofbirth_date" formControlName="dateofbirth_date"  placeholder="Pick Date of Birth" />
                                        <span class="error-msg" *ngIf="emplyeeManagementAddForm.controls.dateofbirth_date.invalid && (emplyeeManagementAddForm.controls.dateofbirth_date.touched || emplyeeManagementAddForm.controls.dateofbirth_date.valid)">
                                        Please Select Date of Birth.
                                    </span>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3 formfieldbox">
                                <div class="form-group">
                                    <label>Select Gender</label>
                                    <input type="radio" class="styled" formControlName="employee_gender" value="Male" name="employee_gender"> Male
                                    <input type="radio" class="styled" formControlName="employee_gender" value="Female" name="employee_gender"> Female
                                    <span class="error-msg" *ngIf="emplyeeManagementAddForm.controls.employee_gender.invalid && (emplyeeManagementAddForm.controls.employee_gender.touched || emplyeeManagementAddForm.controls.employee_gender.valid)">
                                        Please Select Gender.
                                    </span>
                                </div>
                            </div>
                            <div class="col-md-3 formfieldbox">
                                <div class="form-group customSelect2 simpleSelect2">
                                    <label>Marital Status</label>
                                    <select class="form-control" name="employee_marital" formControlName="employee_marital" id="employee_marital" data-placeholder="Select Marital Status" (change)="getMaritalStatus($event.target.value)">
                                        <option value="">Please Select Marital Status</option>
                                        <option value="Single">Single</option>
                                        <option value="Married">Married</option>
                                        <option value="Windowed">Widowed</option>
                                        <option value="Divorced/Separated">Divorced / Separated</option>
                                    </select>
                                    <span class="error-msg" *ngIf="emplyeeManagementAddForm.controls.employee_marital.invalid && (emplyeeManagementAddForm.controls.employee_marital.touched || emplyeeManagementAddForm.controls.employee_marital.valid)">
                                        Please Select Marital Status.
                                    </span>
                                </div>
                            </div>
                            <div class="col-md-3 formfieldbox" *ngIf="maritalDateDiv">
                                <div class="form-group">
                                    <label>Marital Date</label>
                                    <div class="input-group selectMultiDates2">
                                       <span class="input-group-addon">
                                           <i class="glyphicon glyphicon-calendar"></i>
                                       </span>
                                       <input readonly="" id="marital_date" bsDatepicker [bsConfig]="{ dateInputFormat: 'YYYY-MM-DD' }" [maxDate]="maxDate" class="form-control selectdate" name="marital_date" formControlName="marital_date" placeholder="Pick Date of Birth" />
                                    </div>
                                    <span id="maritalDateErrorDiv" class="error-msg"></span>
                                </div>
                            </div>
                            <div class="col-md-3 formfieldbox">
                                <div class="form-group">
                                    <label>Education </label>
                                    <input type="text" name="employee_education" formControlName="employee_education" placeholder="Employee Education" class="form-control" />
                                    <span class="error-msg" *ngIf="emplyeeManagementAddForm.controls.employee_education.invalid && (emplyeeManagementAddForm.controls.employee_education.touched || emplyeeManagementAddForm.controls.employee_education.valid)">
                                        Please Select Education.
                                    </span>
                                </div>
                            </div>
                            <div class="col-md-3 formfieldbox">
                                <div class="form-group">
                                    <label>Work Experience </label>
                                    <input type="text" name="work_experience" formControlName="work_experience" placeholder="Work Experience" class="form-control" />
                                    <span class="error-msg" *ngIf="emplyeeManagementAddForm.controls.work_experience.invalid && (emplyeeManagementAddForm.controls.work_experience.touched || emplyeeManagementAddForm.controls.work_experience.valid)">
                                        Please Select Work Experience.
                                    </span>
                                </div>
                            </div>
                            <div class="col-md-3 formfieldbox">
                                <div class="form-group">
                                    <label>Upload Profile Pic </label>
                                    <input type="file" name="profile_pic" (change)="selectFile($event)" accept="image/x-png,image/jpeg" formControlName="profile_pic" placeholder="Work Experience" class="form-control" />
                                    <input type="hidden" id="saveProfilePicInput" name="saveProfilePicInput" formControlName="saveProfilePicInput" [value]="saveProfilePicInput" />
                                    <span id="savePicErrorDiv" class="error-msg"></span>
                                </div>
                            </div>
                            <div class="col-md-12 formfieldbox">
                                <div class="form-group">
                                    <label>Address</label>
                                    <textarea name="employee_address" formControlName="employee_address" rows="1" cols="5" placeholder="Flat/Floor Number, Building Name, Nearest Landmark" class="form-control"></textarea>
                                    <span class="error-msg" *ngIf="emplyeeManagementAddForm.controls.employee_address.invalid && (emplyeeManagementAddForm.controls.employee_address.touched || emplyeeManagementAddForm.controls.employee_address.valid)">
                                        Please Enter Address.
                                    </span>
                                </div>
                            </div>
                        </div>
                    </fieldset>
                </div>                          
            </div>
            <div>{{statusCode}}</div>
            <div class="text-right">
                <button type="reset"  class="btn btn-primary resetbtn">Reset</button>
                <button type="submit" [disabled]="!emplyeeManagementAddForm.valid" class="btn btn-primary submitbtn">Submit</button>
            </div>
        </div>
    </div>
</form>
---------------------------------------------------------------------------------------------
12) Table List with filter,pagination, count record and edit/delete:

 app.module.ts file
    import { FilterdataPipe } from './filterdata.pipe';
    declarations: [
        FilterdataPipe
    ]   
    //searching filter pipe ts file
    filterdata.pipe.ts attach file is https://goo.gl/Afv1VL
  
    component.ts file
    queryString = "";
    employeeLoader = false;
      employeeList: any[];
    itemlistForRecord = ['100','250','500','1000'];
    itemsCountPerPage = this.itemlistForRecord[0];
    p: number = 1;
  
    constructor(private apiService: ApiService, private router: Router, private localSt:LocalStorageService){}
  
    ngOnInit(){
        this.getAllEmployeeList();
      }
  
    //fetch all record
    getAllEmployeeList(){
        let sendEmployeeListData = {
          'method'  : btoa('employeeList')
        };
        this.employeeLoader = true;
       this.apiService.checkDataToServerFunction(sendEmployeeListData)
       .subscribe(data => {
            this.employeeList = data.employeeList;
            this.employeeLoader = false;
       });
    }
  
    //Delete data
       deleteEmployee(deleteId: string) {
       var result = confirm('Are sure want to update record?');
       if(result == true){

               let mySetItem = this.localSt.retrieve('user_id');
               this.employeeLoader = true;
               let sendEmployeeDeleteData = {
                  'method'          : btoa('deleteEmployee'),
                  'employee_id'   : deleteId,
                  'user_id'          : mySetItem
            };
            console.log(sendEmployeeDeleteData);
        this.apiService.checkDataToServerFunction(sendEmployeeDeleteData)
            .subscribe(data => {
                this.employeeLoader = false;
                this.getAllEmployeeList();  
            });
       }
       }
  
    //edit data
    loadEmployeeToEdit(editId: string){
           this.employeeLoader = true;
           let sendEmployeeEditData = {
              'method'          : btoa('editEmployee'),
              'employee_id'   : editId
        };

        this.apiService.checkDataToServerFunction(sendEmployeeEditData)
            .subscribe(data => {
                console.log(data);
                let userInfo = data.userInfo[0];
                this.emplyeeManagementAddForm.setValue({
                      'user_id'                  : userInfo.user_id,
                      'employee_name'          : userInfo.user_name,
                      'employee_email_id'      : userInfo.email_id,
                      'mobile_number'          : userInfo.mobile_number,
                      'dateofbirth_date'      : userInfo.dob,
                      'employee_gender'          : userInfo.gender,
                      'employee_marital'      : userInfo.marital_status,
                      'marital_date'          : userInfo.anniversary_date,
                      'employee_education'      : userInfo.education,
                      'work_experience'          : userInfo.work_experience,
                      'profile_pic'               : "",
                      'saveProfilePicInput'    : userInfo.avatar,
                      'employee_address'      : userInfo.address
                });
                this.getMaritalStatus(userInfo.marital_status);
                this.employeeLoader = false;
        });
       }
  
    component.html file
    <div class="table-responsive tableview-main">
        <div class="fullwidth filterArea">
            <div class="selectlist customSelect2 tableSelect2">
                <select  [(ngModel)]="itemsCountPerPage" class="selectbx" name="itemsCountPerPage" >
                    <option *ngFor="let s of itemlistForRecord" [ngValue]="s">{{s}}</option>
                </select>
            </div>
            <div class="tableSearch">
                <div class="form-group">
                    <input type="text" [(ngModel)]="queryString" class="form-control" placeholder="Search..." />
                </div>
            </div>
        </div>
        <div class="customTable customertable">
            <div class="fullwidth tablebox">
                <table width="100%" border="1" class="table table-striped table-bordered export-table-customer">
                    <thead>
                        <tr>
                            <th>Sr. No.</th>
                            <th>Employee Name</th>
                            <th>Unique ID</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr *ngFor="let cust of employeeList | filterdata: queryString | paginate: { itemsPerPage: itemsCountPerPage, currentPage: p}; let ind = index;">
                            <td>{{(itemsCountPerPage * (p-1)) + ind + 1}}</td>
                            <td>{{cust.user_name}}</td>
                            <td>{{cust.user_unique_id}}</td>
                            <td>
                                <span ><button type="button" (click)="loadEmployeeToView(cust.user_id)">View</button> </span>
                                /
                                <span ><button type="button" (click)="loadEmployeeToEdit(cust.user_id)">Edit</button> </span>
                                /
                                <span ><button type="button" (click)="deleteEmployee(cust.user_id)">Delete</button> </span>
                            </td>
                        </tr>
                        <tr class="alert alert-danger center text-center" *ngIf='(employeeList | filterdata: queryString)?.length === 0'>
                            <td colspan="4">
                                <span >Sorry , No Data Found</span>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
        <div class="fullwidth paginationbox">
            <div class="showingPage pull-left">
                Showing
                <span *ngIf="(employeeList | filterdata: queryString)?.length == '0'">
                    0
                </span>
                <span *ngIf="(employeeList | filterdata: queryString)?.length != '0'">
                    {{(itemsCountPerPage * (p-1)) + 1}}
                </span>
                to
                <span *ngIf="(employeeList | filterdata: queryString)?.length == employeeList?.length">
                    <span *ngIf="employeeList?.length > itemsCountPerPage * p">
                        {{itemsCountPerPage * p}}
                    </span>
                    <span *ngIf="employeeList?.length < itemsCountPerPage * p">
                        {{(employeeList?.length - (itemsCountPerPage * (p-1))) + (itemsCountPerPage * (p-1))}}
                    </span>
                </span>
                <span *ngIf="(employeeList | filterdata: queryString)?.length != employeeList?.length">
                    {{(employeeList | filterdata: queryString)?.length}}
                </span>
                 of {{employeeList?.length}} entries
            </div>
            <pagination-controls (pageChange)="p = $event"></pagination-controls>
        </div>
    </div>
---------------------------------------------------------------------------------------------
13) Pipes:
-> pipe is filter data, you can modified data in uppercase, lowercase, change date format

---------------------------------------------------------------------------------------------
14) http:

 app.module.ts file
 import { HttpClientModule } from '@angular/common/http';
 imports: [
    HttpClientModule
 ]

component.ts file
 import { HttpClient } from '@angular/common/http';
 constructor(private http: HttpClient){}
---------------------------------------------------------------------------------------------
15) Service:
If create new service then use command
 > ng generate service Api
or
> ng g s Api

-> then name of api service generated in src->app folder directory and create two file name like api.service.ts, api.service.spec.ts

api.service.ts attach file is https://goo.gl/Nf133d

app.module.ts file
import { ApiService } from './api.service';
providers: [ApiService]
 
employee.component.ts file
import { ApiService } from './../api.service';
constructor(private apiService: ApiService){}
---------------------------------------------------------------------------------------------
16) Directive:
create directive then use command
 > ng generate directive highlight

 (validation for input onlyNumber, onlyCharacter, not Special Character)
app.module.ts file
import { NumberOnlyDirective } from './number-only.directive';
import { CharacterOnlyDirective } from './character-only.directive';
import { AlphanumberonlyDirective } from './alphanumberonly.directive'; 

declarations: [
    NumberOnlyDirective,
    CharacterOnlyDirective,
   AlphanumberonlyDirective
]

number-only.directive.ts attach file is https://goo.gl/bxRzrt

character-only.directive.ts attach file is https://goo.gl/nfaFV2

alphanumber-only.directive.ts attach file is https://goo.gl/JQ2Sbm
 
component.html file
For Number :
<input type="text" myNumberOnly id="mobile_number" formControlName="mobile_number" name="mobile_number" minlength="10" maxlength="10" placeholder="9999999999" class="form-control" />

For Character :
<input type="text" myCharacterOnly name="employee_name"  formControlName="employee_name" placeholder="Enter Employee Name" class="form-control" />

For Alpha Number:
<input type="text" myAlphanumberonly name="employee_id"  formControlName="employee_id" placeholder="Enter Employee Id Number" class="form-control" />

---------------------------------------------------------------------------------------------
17) Datepiker:
(mydatepicker = https://www.npmjs.com/package/angular4-datepicker)

bsDatepicker coding :
 CMD TO Run Command
 > npm install ngx-bootstrap --save
 > npm install bootrap@3 --save (all ready install when setup run)

app.module.ts file
import { BsDatepickerModule } from 'ngx-bootstrap';
imports: [
    BsDatepickerModule.forRoot()
]

angular.cli.json file
"styles": [
    "../node_modules/bootstrap/dist/css/bootstrap.min.css",
    "../node_modules/ngx-bootstrap/datepicker/bs-datepicker.css",

    "src/styles.css"
]

index.html file
<link rel="stylesheet" href="https://unpkg.com/ngx-bootstrap/datepicker/bs-datepicker.css">

app.component.ts file
for date range validation to use :
    minDate = new Date(2018, 5, 10);
    maxDate = new Date(2018, 9, 15);

below to constructor

app.component.html file
->for single datepiker
<input bsDatepicker type="text" [bsConfig]="{ dateInputFormat: 'YYYY-MM-DD' }" [minDate]="minDate" [maxDate]="maxDate" name="dob" formControlName="dob" />
->for daterange picker
<input bsDaterangepicker type="text" name="dob" formControlName="dob" />
---------------------------------------------------------------------------------------------
18) upload file:
component.ts file
selectedFiles: FileList;
currentFileUpload: File;
  
selectFile(event) {
    this.selectedFiles = event.target.files;
}
upload() {
    this.currentFileUpload = this.selectedFiles.item(0);
    this.articleService.pushFileToStorage(this.currentFileUpload,'uploadFileAngular').subscribe(event => {
     if (event instanceof HttpResponse) {
        console.log('File is completely uploaded!');
      }
    });
    this.selectedFiles = undefined;
}

component.html file
<div style="text-align:center">
    <label>
        <input type="file" (change)="selectFile($event)">
    </label>
    <button [disabled]="!selectedFiles" (click)="upload()">Upload</button>
</div>
---------------------------------------------------------------------------------------------
19) Filter:
use command
> ng g pipe filterdata
for date pipe  {{dob | date: 'dd-MM-yyyy'}}
---------------------------------------------------------------------------------------------
20) Pagination:

Referance to use url : https://ciphertrick.com/2017/08/01/search-sort-pagination-in-angular/

use command
> npm install ngx-pagination --save

app.module.ts file
import {NgxPaginationModule} from 'ngx-pagination';
imports: [
    NgxPaginationModule
]

component.ts file
p: number = 1;

component.html
<tr *ngFor="let cust of employeeList | paginate: { itemsPerPage: itemsCountPerPage, currentPage: p}; let ind = index;">
    <td>{{(itemsCountPerPage * (p-1)) + ind + 1}}</td>
    <td>{{cust.user_name}}</td>
    <td>{{cust.user_unique_id}}</td>
    <td>
        <span ><button type="button" (click)="loadEmployeeToView(cust.user_id)">View</button> </span>
        /
        <span ><button type="button" (click)="loadEmployeeToEdit(cust.user_id)">Edit</button> </span>
        /
        <span ><button type="button" (click)="deleteEmployee(cust.user_id)">Delete</button> </span>
    </td>
</tr>
<pagination-controls (pageChange)="p = $event"></pagination-controls>
---------------------------------------------------------------------------------------------
21) redirect to url base on component function:

app.module.ts file
import { RouterModule, Router, Routes, ActivatedRoute } from '@angular/router';
RouterModule.forRoot([
    {
        path: '',
        component : LoginComponent
    },
    {
        path: 'dashboard',
        component : DashboardComponent
    }
])

employee.component.ts file
import { RouterModule, Router } from '@angular/router';
import { ActivatedRoute } from "@angular/router";

constructor(private router: Router,private route: ActivatedRoute){}

goToCustomer(){
    this.router.navigate(["customer"]);
}

employee.component.html file
<button type="button" (click)="goToCustomer()">Go To Customer</button>
---------------------------------------------------------------------------------------------
22) active class apply base on url:

<li [routerLinkActive]="['active']">
    <a routerLink="/dashboard" title="Dashboard">
        <i class="menuIcons icon-dashboard"></i>
        <span>Dashboard</span>
    </a>
</li>
---------------------------------------------------------------------------------------------
23) url to pass parameter:

app.module.ts  file
import { RouterModule, Router, Routes, ActivatedRoute } from '@angular/router';
RouterModule.forRoot([
    {
        path: '',
        component : LoginComponent
    },
    {
        path: 'customer/:id',
        component : CustomerComponent
    }
])

component.ts file
import {ActivatedRoute} from "@angular/router";

id= "customer.html";
constructor(private route: ActivatedRoute) {}

//by function
this.router.navigate(["customer",this.id]);

component.html file
//by routing
<a [routerLink]="['/customer', 'customer.html']" title="Customers">Customer</a>

output : http://localhost:4200/customer/customer.html
---------------------------------------------------------------------------------------------
24) cookies, session and localstorage:
refer link : https://www.youtube.com/watch?v=FKPfiQQz5hY

-> local starage to set data parmenant, cookies and session data store temporary
-> deference between cookie localstorage  session
    cookies : set data then tab close then also cookies store but brower close then cookies remove
    local store : tab close or browser close but data not remove untill user not clear local storage
    session : tab close or browser close then data remove

cookies :
use command > npm install angular2-cookie --save
   
session and local storage :
use command > npm install ngx-webstorage --save

app.module.ts file
    import { CookieService } from 'angular2-cookie/services/cookies.service'; //for cookies
    import { Ng2Webstorage } from 'ngx-webstorage'; //for session and localstorage
   
    imports: [
        Ng2Webstorage
    ]
   
    providers: [CookieService]

component.ts file
    import { CookieService } from 'angular2-cookie/core'; //for cookies
    import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; //for session and localstorage
   
    constructor(private _cookieService: CookieService, private sessionSt: SessionStorageService, private localSt:LocalStorageService){}

   //cookies
    setCookies(){
        this._cookieService.put('test','testing cookies');
    }
   

    getCookies(){
        this._cookieService.get('test');
    }   
    delCookies(){
        this._cookieService.remove('test');
    }

   
    //Session
    setSessionStorage(){
        this.sessionSt.store('logged-in','user');
    }
    getSessionStorage(){
        this.sessionSt.retrieve('logged-in');
    }
    delSessionStorage(){
        this.sessionSt.clear('logged-in');
    }

   
    //local storage
    setLocalStorage(){
        this.localSt.store('userName','Abc Xyz');
    }
    getLocalStorage(){
        this.localSt.retrieve('userName');
    }
    delLocalStorage(){
        this.localSt.clear('userName');
    }

---------------------------------------------------------------------------------------------
25) check session set or not in component:
login.cmponent.ts file
import { RouterModule, Router } from '@angular/router';
import { LocalStorageService } from 'ngx-webstorage';

constructor(private router: Router, private localSt:LocalStorageService) { }

ngOnInit() {
    //for local storage value get data code
      let mySetItem = this.localSt.retrieve('user_id');
      if(mySetItem != undefined){
          this.router.navigate(["dashboard"]);
      }

}

dashboard.component.ts file
import { RouterModule, Router } from '@angular/router';
import { LocalStorageService } from 'ngx-webstorage';

constructor(private router: Router, private localSt:LocalStorageService) { }

ngOnInit() {   
      //for local storage value get data code
      let mySetItem = this.localSt.retrieve('user_id');
      if(mySetItem == undefined){
          this.router.navigate([""]);
      }

}
---------------------------------------------------------------------------------------------
26) get service.ts variable value to component.ts file:
refer link : https://stackoverflow.com/questions/34572005/persisting-and-accessing-values-globally-in-multiple-components-in-angular-2

api.service.ts file
fileUrl = "http://localhost/project/images/";

getFilePath() {
    return this.fileUrl;
}

component.ts file
constructor(private apiService: ApiService){}
get filePath() {
    return this.apiService.getFilePath();
}

component.html file
<img src="{{filePath}}uploads/angular4/abc.png" width="50px" height="50px" />
---------------------------------------------------------------------------------------------
27) transfer data one component to other component:

component.html file
<button type="button" (click)="loadEmployeeToView(cust.user_id)">View</button>

one.component.ts
loadEmployeeToView(viewId: string){
    this.employeeLoader = true;
    let sendEmployeeViewData = {
        'method'          : btoa('viewEmployee'),
        'employee_id'   : viewId
    };
    var userRecord = JSON.stringify(sendEmployeeViewData);
    localStorage.setItem("employeeRecord",userRecord);
    this.router.navigate(["viewEmployeeDetails"]);
}

other.component.ts
ngOnInit() {
    this.employeeViewDetailsLoader = true;
    let getEmployeeRecord = JSON.parse(localStorage.getItem("employeeRecord"));
    this.apiService.checkDataToServerFunction(getEmployeeRecord)
    .subscribe(data => {
        this.employee_name         = data.userInfo[0].user_name;
        this.employeeViewDetailsLoader = false;
    });
}
---------------------------------------------------------------------------------------------
28) jQuery in angular:
use command : 
> npm i jquery --save
> npm i @types/jquery -D


app.module.ts file
import * as $ from 'jquery';

component.ts file
declare var jquery:any;
declare var $ :any;


let custname = $("#custname").val();
console.log(custname);

//validation in component
if (($("#email_id").val() == '') || ($("#email_id").val() == undefined)) {
    $('#emailErrorDiv').html("Please Enter Email Id.");
    return false;
} else {
    $('#emailErrorDiv').html("");
}
---------------------------------------------------------------------------------------------
29) Animation:
refer link : https://coursetro.com/posts/code/109/Angular-5-Animation-Tutorial
---------------------------------------------------------------------------------------------
30) Data table:
refer link : https://www.npmjs.com/package/angular-6-datatable

use command :
> npm i angular-6-datatable --save

app.module.ts file
import {DataTableModule} from "angular-6-datatable";
imports: [
    DataTableModule
]

data = [
{name:'abc',email:'abc@gmail.com',age:'20',city:'test'},
{name:'xyz',email:'xyz@gmail.com',age:'22',city:'test 1'}
]

component.html file
<table class="table table-striped" [mfData]="data" #mf="mfDataTable" [mfRowsOnPage]="5">
    <thead>
    <tr>
        <th style="width: 20%">
            <mfDefaultSorter by="name">Name</mfDefaultSorter>
        </th>
        <th style="width: 50%">
            <mfDefaultSorter by="email">Email</mfDefaultSorter>
        </th>
        <th style="width: 10%">
            <mfDefaultSorter by="age">Age</mfDefaultSorter>
        </th>
        <th style="width: 20%">
            <mfDefaultSorter by="city">City</mfDefaultSorter>
        </th>
    </tr>
    </thead>
    <tbody>
    <tr *ngFor="let item of mf.data">
        <td>{{item.name}}</td>
        <td>{{item.email}}</td>
        <td class="text-right">{{item.age}}</td>
        <td>{{item.city | uppercase}}</td>
    </tr>
    </tbody>
    <tfoot>
    <tr>
        <td colspan="4">
            <mfBootstrapPaginator [rowsOnPageSet]="[5,10,25]"></mfBootstrapPaginator>
        </td>
    </tr>
    </tfoot>
</table>
---------------------------------------------------------------------------------------------
31) Deploy to server:
refer link : https://angular.io/guide/deployment
-> ng build
-> ng build --prod
-> ng build --prod --build-optimizer
---------------------------------------------------------------------------------------------
32) Social Login (fb and google):
refer link : https://www.9lessons.info/2018/07/social-login-using-angular-and-restful.html

use command :
> npm install angular-6-social-login --save

app.module.ts file
import {
    SocialLoginModule,
    AuthServiceConfig,
    GoogleLoginProvider,
    FacebookLoginProvider
 } from 'angular-6-social-login';
 export function getAuthServiceConfigs() {
    const config = new AuthServiceConfig([{
        id: FacebookLoginProvider.PROVIDER_ID,
        provider: new FacebookLoginProvider('922140375904491')
    },
    {
        id: GoogleLoginProvider.PROVIDER_ID,
        provider: new GoogleLoginProvider('922146924581-r0bop4bs30aali2i9n46l16077eaekpb.apps.googleusercontent.com')
    }]);
    return config;
}

imports: [
    SocialLoginModule
]

providers: [{
    provide: AuthServiceConfig,
    useFactory: getAuthServiceConfigs
}]
 login.component.ts file
 import {
  AuthService,
  FacebookLoginProvider,
  GoogleLoginProvider
} from 'angular-6-social-login';
constructor(private socialAuthService: AuthService){}
 public socialSignIn(socialPlatform: string) {
    let socialPlatformProvider;
    if (socialPlatform === 'facebook') {
        socialPlatformProvider = FacebookLoginProvider.PROVIDER_ID;
    } else if (socialPlatform === 'google') {
        socialPlatformProvider = GoogleLoginProvider.PROVIDER_ID;
    }
    
    this.socialAuthService.signIn(socialPlatformProvider).then(userData => {
        //  this.apiConnection(userData);
        console.log(userData);

        //for fb
        //email:"emailId@gmail.com"
        //id:"911180812088642210"
        //image:"https://graph.facebook.com/1980812088642210/picture?type=normal"
        //name:"Rajesh Anant Palande"
        //provider:"facebook"
        //token:"too long dfgdfgdfgdf........"

        //for google
        // email:"emailId@gmail.com"
        // id:"91126323876025066138091"
        // idToken:"too long qwdess......"
        // image:"https://lh5.googleusercontent.com/-YAyWj4bQpwI/AAAAAAAAAAI/AAAAAAAAAOA/bKOb0j9XPJE/s96-c/photo.jpg"
        // name:"Rajesh Palande"
        // provider:"google"
        // token:"too long fgfgfgfdgfd....."
    });
}
login.component.html file
<button (click)="socialSignIn('facebook')" class="btn btn-social btn-facebook">
    <span class="fa fa-facebook"></span> Sign in with Facebook
</button>
<button (click)="socialSignIn('google')" class="btn btn-social btn-google">
    <span class="fa fa-google"></span> Sign in with Google
</button> 

create fb credential
URL : https://developers.facebook.com/apps

---------------------------------------------------------------------------------------------  
 33) post angular file base64 with other data (file + input data) :
refer link :
https://nehalist.io/uploading-files-in-angular2/
https://stackoverflow.com/questions/39272970/angular-2-encode-image-to-base64 

component.ts file
 selectedFileBase: {};
 selectedFileName: string = null;

userManagementAddForm = new FormGroup({
        employee_id : new FormControl(""),
        user_name      : new FormControl("",Validators.required),
        user_dob      : new FormControl("",Validators.required),
        avatar         : new FormControl("")
});

//only file code start
propagateChange = (_: any) => { };
registerOnChange(fn) {
        this.propagateChange = fn;
        console.log(this.propagateChange);
}
registerOnTouched() { }

changeListener($event) : void {
        this.userLoader = true;
        this.readThis($event.target);
}

readThis(inputValue: any): void {
        var file:File = inputValue.files[0];
        var myReader:FileReader = new FileReader();
 
        myReader.onloadend = (e) => {
            console.log(myReader.result);
            this.selectedFileBase = myReader.result; //here sture 64 base data
            this.selectedFileName = file.name; //file name

        }
        myReader.readAsDataURL(file);
        this.userLoader = false;
}
//only file code end

addEmployeeDetails(userManagementAddForm){
        this.userLoader = true;
        let mySetItem = this.localSt.retrieve('user_id');
        let userSaveData = {
            'method'          : btoa('addUserDetails'),
            'user_name'      : userManagementAddForm.user_name,
            'user_dob'         : userManagementAddForm.user_dob,
            'avatar'        : this.selectedFileBase,
            'file_name'        : this.selectedFileName,
            'login_user_id' : mySetItem
        };
        console.log(userSaveData);

        this.apiService.checkDataToServerFunction(userSaveData)
        .subscribe(data => {
            console.log(data);
            this.userManagementAddForm.reset();   
              this.userLoader = false;
            this.getAllUserList();
        });
}

component.html file
<form autocomplete="off" name="userManagementAddForm" id="userManagementAddForm" [formGroup] = "userManagementAddForm" (ngSubmit)="addEmployeeDetails(userManagementAddForm.value)" >
        <fieldset>
            <input type="hidden" formControlName="employee_id" name="employee_id" id="employee_id"  class="form-control" />
            <div class="row">
                <div class="col-md-3 formfieldbox">
                    <div class="form-group">
                        <label>User Name</label>
                        <input type="text" myCharacterOnly name="user_name"  formControlName="user_name" placeholder="EnterUser Name" class="form-control" />
                        <span class="error-msg" *ngIf="userManagementAddForm.controls.user_name.invalid && (userManagementAddForm.controls.user_name.touched || userManagementAddForm.controls.user_name.valid)">
                            Please Enter Name.
                        </span>
                    </div>
                </div>
                <div class="col-md-3 formfieldbox">
                    <div class="form-group">
                        <label>DOB</label>
                        <input type="text" myCharacterOnly name="user_dob"  formControlName="user_dob" placeholder="EnterUser Name" class="form-control" />
                        <span class="error-msg" *ngIf="userManagementAddForm.controls.user_dob.invalid && (userManagementAddForm.controls.user_dob.touched || userManagementAddForm.controls.user_dob.valid)">
                            Please Enter DOB.
                        </span>
                    </div>
                </div>
                <div class="col-md-3 formfieldbox">
                    <div class="form-group">
                        <label>Upload Profile Pic </label>
                        <input type="file" name="profile_pic" (change)="changeListener($event)"  formControlName="profile_pic" placeholder="Profile Picture" class="form-control" />
                    </div>
                </div>
            </div>
        </fieldset>
        <div class="text-right">
            <button type="reset"  class="btn btn-primary resetbtn">Reset</button>
            <button type="submit" [disabled]="!userManagementAddForm.valid" class="btn btn-primary submitbtn">Submit</button>
        </div>
    </form>

php catch data 
$avatar = $requestData['avatar'];
$file_name = $requestData['file_name'];
$expoldeFileName = explode('.', $file_name);
$fileExtention = $expoldeFileName[1];
    
$folderPath = 'uploads/angular4/';
$image_parts = explode(";base64,", $avatar);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$file = $folderPath . uniqid() . '.'.$fileExtention;
$fileName = uniqid() . '.'.$fileExtention;
file_put_contents($file, $image_base64); 
--------------------------------------------------------------------------------------------- 
 34) .htaccess file :
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /cmsnew/
    RewriteRule ^index\.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /cmsnew/index.html [L]
</IfModule>
--------------------------------------------------------------------------------------------- 
 35) create component in folder like (include/header) :
use command :
> ng g c includes/header 
---------------------------------------------------------------------------------------------

2 comments: