Tuesday, November 14, 2023

Working with Pagination when using Ajax in Angular

 Splitting bulk amount of data into smaller blocks is called "pagination | paging",

this blocks are called pages, only one page records will be shown to the user at a time

Page index will start with 0

 collection -->pagesize-10---> page1-10 recs[0] ----> only single page recs 

display[10 recs]
  [100 recs]                   page2-10 recs[1]           <  <<  >>  >[navigation buttons]
                                      ...
                                     page9-10 recs[9]


Paging can be implemented in angular using ngx-pagination package, this is
 providing ngxpaginationmodule with a pipe and component
 
1.paginate pipe--this will split a collection into pages using items Per Page property, it will display page records based on currentPage property

 2.pagination-controls component--this will provide navigation buttons to
                                  provide navigation between pages


Goto terminal to install ngx-pagination package
 
npm i ngx-pagination













For this example, i am going to use the below url 


http://dummy.restapiexample.com/api/v1/employees












Goto 

https://jsonviewer.stack.hu/































create a component to display employees data getting from restapi available


ng g c employees --flat




Employee.ts

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './employees.component.html',
  styleUrls: ['./employees.component.css']
})
export class EmployeesComponent implements OnInit {
  res:any;
  pagenumb:number=0;
  constructor(private _httpclient:HttpClient)
  {
   this._httpclient.get("http://dummy.restapiexample.com/api/v1/employees").subscribe(
     (response:any)=>{
       this.res=response;
     }
   );
  }
 m1(pagenumb1:number)
  {
    this.pagenumb=pagenumb1;
  }
  ngOnInit(): void {
    throw new Error('Method not implemented.');
  }
}


.html

<h1> Employee Data</h1>
<table style="font-size:x-large" border="1">
    <tr>
        <th>name</th>
        <th>salary</th>
        <th>age</th>
    </tr>
    <tr *ngFor="let e of res.data |paginate:{itemsPerPage:10,currentPage:pagenumb}">
      <td>
          {{e.employee_name}}
      </td>
      <td>
       {{e.employee_salary}}
   </td>
   <td>
       {{e.employee_age}}
   </td>
    </tr>
    <tr>
        <td colspan="3" style="text-align: center;">
         <pagination-controls (pageChange)="m1($event)"></pagination-controls>
       </td>
    </tr>
   </table>


appModule.ts


import{NgxPaginationModule} from "ngx-pagination";
import{HttpClientModule} from "@angular/common/http";
@NgModule({ ... imports:[...,NgxPaginationModule,HttpClientModule],
 bootstrap:[EmployeesComponent]
})


Output


























Note:

In case , if you are getting CORS Error, then use chrome browser and go to the installed path
and type the below command

chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security

Second Approach to fix that issue ,is to fix CORS Error


https://www.stackhawk.com/blog/angular-cors-guide-examples-and-how-to-enable-it/



initial pagenumb is 0,so currentpage prop is set with 0,so paginate pipe
 will display 1st page recs

*navigation button click[next|prev] will call pageChange event method m1,$event
 keyword will provide page numb based on navigation button click, this will be
 be assigned pagenumb variable, accordingly current page will change to display
 page recs




Working with AJAX In Angular

 AJAX[Asynchronous Javascript And XML]

-------------------------------------
Ajax provides asynchronous communication with server[or webserver] to send|get
 required data
Asynchornous communication allows performing more than one task parallely
Eg:
   username availability
   cascading dropdown
       ...
Advantages:
  1.asynchronous communication[parallel exec]
  2.user state will be maintained by avoiding page reload|refresh
    [better user experience]
  3.reduces network traffic and burden on server
 
There are different ways to work with ajax
 1.manual approach using javascript[xmlhttprequest component]
 2.jquery ajax[$.ajax function]
 3.angular ajax[httpclient service]


Http Client service:
-------------------
*Angular2 was providing Http  service to work with ajax
*Angular5+ is providing Http Client service to work with ajax, Http service is  deprecated

*Http Client service is simple, light weight and more powerful over Http service
     simple-->easy to user[developer friendly]
     light weight-->consumes less memory resources
     powerful   -->it supports Http Interceptor middleware service

*Http Client service can be used to perform an ajax call to rest api methods
 to perform crud operations with datastore
*Http Client  service is providing set of methods to call rest api methods
 1.get(restapiurl)--it will call rest api get method to get all the recs (or) rec based on a condition

 2.post(restapiurl,object)--it will call rest api post method to insert a rec
 
 3.put(restapiurl,object)--it will call rest api put method to update | modify a rec

 4.delete(restapiurl)--it will call rest api delete method to delete a rec


HttpClient service methods will return Observable, register callback function
 using subscribe method to read restapi method response

 syntax:
   this._httpclient.<methodname>(restapiurl,..).subscribe(
            (posresponse)=>{
                            callback function to read positive response[data]
                            provided by restapi method
                           },
            (errorresponse)=>{
                            callback function to read error response
                            provided by restapi method
                             },
                   ()=>{
                        complete callback func
                       }
                );


There are so many third party restapi's are available on internet

https://www.w3schools.com/angular/customers.php
https://reqres.in/api/users
https://jsonplaceholder.typicode.com/todos
https://restcountries.eu/rest/v2/all
    |
   name
ngmusicdb.herokuapp.com/api/getMusic

http://dummy.restapiexample.com/api/v1/employees
https://api.covid19api.com/summary
https://api.exchangeratesapi.io/latest


For this example, i am going to use the below url 


http://dummy.restapiexample.com/api/v1/employees









Goto 

https://jsonviewer.stack.hu/
























create a component to display employees data getting from restapi available
on internet server


ng g c employees --flat


Employee.ts

import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './employees.component.html',
  styleUrls: ['./employees.component.css']
})
export class EmployeesComponent {
  res:any;

  constructor(private _httpclient:HttpClient)
  {
    this._httpclient.get("http://dummy.restapiexample.com/api/v1/employees").subscribe(
     (response:any)=>{
       this.res=response;
     }
    );
  }
}


.html

<h1> Employee Data</h1>
<table style="font-size:x-large" border="1">
    <tr>
        <th>name</th>
        <th>salary</th>
        <th>age</th>
    </tr>
    <tr *ngFor="let e of res.data">
      <td>
          {{e.employee_name}}
      </td>
      <td>
       {{e.employee_salary}}
   </td>
   <td>
       {{e.employee_age}}
   </td>
    </tr>
   </table>


AppModule.ts

import{HttpClientModule} from "@angular/common/http";
@NgModule({
    ...
 imports:[...,HttpClientModule],
 bootstrap:[EmployeesComponent]
   })
   ...



Output


























In case , if you are getting CORS Error, then use chrome browser and go to the installed path
and type the below command

chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security

Second Approach to fix that issue ,is to fix CORS Error


https://www.stackhawk.com/blog/angular-cors-guide-examples-and-how-to-enable-it/

note:
-----
*HttpClient service is provided with @angular/common/http package,this
 requires HttpClientModule
*exec flow:

  browser                  AngularLiveDevelopment server
        ------------------->angularapp[port-4200]
        <-------------------
 angular app
  exec
[employees
 component exec]--------------------------------------webserver
                     internet                        restapi method
                <-------------------------------------{..}------------------>database
                    employees data
     |
reading response with
in callback func
     |
presentation

Thursday, November 9, 2023

Angular Material

Angular material is a UI component library|package to provide rich user interaction

 with angular app
Angular material is providing so many built in components and directives to provide better look and feel

Angular material is an alternative to bootstrap css

  angular material------> native | built in with angular[provided by angular team]
                          less responsive

   bootstrap css -------> third party css framework[provided by twitter]
                           more responsive

*angular material will use angular animations internally
*angular material is based on angular cdk[component development kit]

   raw gold[biscuit gold]-->mould----->ornaments [chain,ring,...]

   angular cdk[raw level]-->moulded--->datepicker,tabcontainer,..[components-->material]

angular material is providing following components | directives:
 1.mat-button         --rectangular text based button without elevation
 2.mat-raised-button  --rectangular text based button with elevation
 3.mat-icon-button    --circular button with transparent color to show icon, this requires

 mat-icon component
                       syntax:
                          <button mat-icon-button>
                             <mat-icon>
                               iconname  [edit,delete,favorite,..]
                             </mat-icon>
                           </button>

icon names are predefined, this can be downloaded from
        http://fonts.googleapis.com/icon?family=Material+Icons


4.matTooltip--this will display fancy tooltip
 5.mat-card  --this is a container to group related text, controls,..
 6.mat-form-field--this is used to apply text based styling like floating text, underline,
                   icon, hint,..
 7.matInput     --this should be applied to textbox or text area to apply mat-form-field
                  text based styling[like floating text,..] 


syntax:
         <mat-form-field>
              <input type="text" matInput>
              <mat-icon matSuffix>iconname</mat-icon>
                 ...
         </mat-form-field>

8.mat-spinner--this is used to display spinner[animated circle]


Example 


Go to command prompt and install the animations package as 
ng add @angular/material


















Next check, with this below command 

>npm i @angular/material









npm i @angular/cdk










angular material installation will provide built-in CSS files

node_modules/@angular/material/prebuilt-themes/indigo-pink.css

 this css will provide color options like primary, warn,..

You can see that it  is automatically reflected in the angular.json file as shown below









*goto src folder and select styles.css
/* You can add global styles to this file, and also import other style files */
@import "~@angular/material/prebuilt-themes/indigo-pink.css";

styles.css







Note:
-----
->the style files imported into styles.css will be global through out the project
-> ~ symbol will substitute node_modules/ 



Example

*create a component
  >ng g c demo --flat









demo Component.html

<button mat-button color="primary">Login</button> <br>
<button mat-raised-button color="primary" matTooltip="save user details">Register</button> <br>
<button mat-icon-button color="warn">
    <mat-icon>
        favorite
    </mat-icon>
</button>
<br>
<mat-card>
    <mat-form-field>
        <input matInput placeholder="username">
        <mat-icon matSuffix>person_outline</mat-icon>
        <mat-hint>username is case sensitive</mat-hint>
    </mat-form-field>
</mat-card>
<br>
<mat-tab-group>
    <mat-tab label="news">
        <h3>display new info</h3>
    </mat-tab>
    <mat-tab label="sports">
        <h3>display sports info</h3>
    </mat-tab>
    <mat-tab label="shares">
        <h3>display shares info</h3>
    </mat-tab>
</mat-tab-group>
<br>
<mat-spinner color="primary"></mat-spinner>


*goto app.module.ts
    ...
import{MatButtonModule} from "@angular/material/button";
import{MatIconModule} from "@angular/material/icon";
import{MatTooltipModule} from "@angular/material/tooltip"
import{MatCardModule} from "@angular/material/card";
import{MatFormFieldModule} from "@angular/material/form-field";
import{MatInputModule} from "@angular/material/input";
import{MatTabsModule} from "@angular/material/tabs";
import{MatProgressSpinnerModule} from "@angular/material/progress-spinner";
import{BrowserAnimationsModule} from "@angular/platform-browser/animations";
@NgModule({
     ..
imports:   [ BrowserModule,MatButtonModule,MatIconModule,MatTooltipModule,MatCardModule,MatFormFieldModule,MatInputModule,MatTabsModule,MatProgressSpinnerModule,BrowserAnimationsModule
  ],
  ..
bootstrap:[DemoComponent]
    })
  ...





Output












Note:
-----

Material.angular.io is a official website of angular material, this will provide
  samples for different material components
              browser
           material.angular.io
                  |
              components
...
datepicker-------   basic datepicker
                                            <>[view code]
                                             |
                                   ....         -->copy code



















goto demo.component.html
   <mat-form-field appearance="fill">        --> paste datepicker component code
    <mat-label>Choose a date</mat-label>
    <input matInput [matDatepicker]="picker">
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker></mat-datepicker>
  </mat-form-field>
  <br>


import{MatDatepickerModule} from "@angular/material/datepicker";
import{MatNativeDateModule} from "@angular/material/core";
@NgModule({
    ...
 imports:[...,MatDatepickerModule,MatNativeDateModule]
    ...
     })
   ...


Output








Kubernetes

Prerequisites We assume anyone who wants to understand Kubernetes should have an understating of how the Docker works, how the Docker images...