Sunday, January 5, 2020

Mat Table Angular

Mat Table in Angular


Mat table is used to display data . its a material designed styled data-table . For using Material Table MatTableModule need to install/add in project.

import {MatTableModule} form '@angular/material'


For using this you need to install Angular Material

ng add @angular/material

C:\AngularService\myservice> ng add @angular/material

Installing packages for tooling via npm.
Installed packages for tooling via npm.
? Choose a prebuilt theme name, or "custom" for a custom theme: Purple/Green   
[ Preview: https://material.angular.io?theme=purple-green
]
? Set up HammerJS for gesture recognition? (Y/n) n

You Can Choose any Theme

And you can add/remove HammerJS also

Set up browser animations for Angular Material? (Y/n) Y


App.Module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
import { EmpserviceService } from './empservice.service';
import { MycomComponent } from './mycom/mycom.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import {MatTableModulefrom '@angular/material/table';
import { EmpdetailsComponent } from './empdetails/empdetails.component'
@NgModule({
  declarations: [
    AppComponent,
    MycomComponent,
    EmpdetailsComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    BrowserAnimationsModule,
    MatTableModule
  ],
  providers: [HttpClientModule,EmpserviceService],
  bootstrap: [AppComponent]
})
export class AppModule { }

App.Component.Html


<h1 align = "center">Mat Table in Angular</h1>
<h3 align = "center">Shubh Techno Expert </h3>
<h3 align = "center">http://xafdeveloper.blogspot.com </h3>
<h3 align = "center">http://ShubhTechnoExpert.blogspot.com </h3>

<button type = "button" (click) ="GetEmpDetails()"  align ="Center"  >Click Me To Display Data</button>

<br>

<div align = "center" >
    <table mat-table [dataSource]="dataSource" border ="3"  >
    
        <ng-container matColumnDef="EmpName" >
            <th  mat-header-cell *matHeaderCellDef >Employee Name</th>
            <td mat-cell *matCellDef="let item">{{item.EmpName}}</td>
        </ng-container>

        <ng-container matColumnDef="EMPCode">
            <th  mat-header-cell *matHeaderCellDef >Employee Code</th>
            <td mat-cell *matCellDef="let item">{{item.EMPCode}}</td>
        </ng-container>
    
        <tr mat-header-row *matHeaderRowDef="columnsToDisplay"></tr>
        <tr mat-row *matRowDef="let row; columns: columnsToDisplay"></tr>
    
    </table>
    </div>


app.component.ts 

import { Component } from '@angular/core';
import {EmpserviceServicefrom './empservice.service'
import {MatTableModule,MatTableDataSourcefrom '@angular/material/table';

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

dataSource = new MatTableDataSource();
columnsToDisplay = ['EmpName''EMPCode'];

constructor(private _EmpserviceService:EmpserviceService){}

  GetEmpDetails(){
  this._EmpserviceService.GetEmployeDetails().subscribe((respp)=>
  {    
     this.dataSource.data = respp;

  })
}
}


Follow us on youtube Shubh Techno Expert 
please subscribe .



Sunday, December 15, 2019

Pagination in Angular

Pagination in Angular


To use Pagination NgxPaginationModule need to install

npm install --save ngx-pagination

once this is installed then add this module in app.module.ts and in import array


app.module.ts 

import { NgxPaginationModule } from  'ngx-pagination';

imports: [
        NgxPaginationModule,
   
    ],


app.Component.Html


in HTML we have create a list item in which we will apply pagination .

we have used paginate event to apply this . in ngFor itemsparpage is used to see how many item will be displayed .

<h1>Employee List</h1>
<ul>

    <li *ngFor = "let item of EmpListcollection | paginate: { itemsPerPage: 10, currentPage: p } " >
    {{item}}

</li>
</ul>

<pagination-controls (pageChange)="p = $event"></pagination-controls>

app.component.ts

in type script file we have created a collection which will be binded in list in HTML component

import { ComponentOnInit } from '@angular/core';
import { stringify } from 'querystring';


@Component({
  selector: 'app-component',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class appComponent implements OnInit {

  EmpListcollection = [];
  mystring : string ;

  constructor() { }

  ngOnInit() {
    
    for (let i =1;i<50;i++)
          {
            this.mystring = 'Angular';
            this.mystring = this.mystring.concat('  Tyepscript ' + i + '.0');
            this.EmpListcollection.push(this.mystring)
          }
  }
}


Output .


Follow us on Shubh Techno Expert 








How to use Service in Angular App

How to call service in  Angular App      


component can not fetch data directly from database. so to fetch data from database API need to call in Angular App . With the help of service we can access method and properties across other component in the entire Projects

1. For this We need a Web API which we will call in our App to access the data .

Syntax to create Service

ng generate service servicename 

API URL : http://localhost:37187/Api/ViewContact/ViewEmpDetails

This API will Return data in Json Format .

    {
        "EMPCode": "E0001",
        "EmpName": "Nagendra1",
        "Email": "Nagendra@gmail.com",
        "Salary": "2500"
    },
   {
        "EMPCode": "E0002",
        "EmpName": "Nagendra2",
        "Email": "Nagendra@gmail.com",
        "Salary": "2700"
    },


Add this Module in App.Module.ts file 

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

and add in import array also

import:[

HttpClientModule

       ]


see this full VDO on youtube on Shubh Techno Expert  Call web API in Angular

app.component.html

Here in HTML added one button in which called a method this method GetEmpDetails() will call the service and return the data .

And taken one table to bind this data .


<h1 align = "center">How to use Service in Angular App</h1>

<button type = "button" (click) ="GetEmpDetails()"  align ="Center" >Click Me</button>

<table border ="3">
    <th>EmpName</th><th>EmpCode</th><th>Salary</th><th>Email</th>

    <tr *ngFor = "let item of EmpServiceresponse">

        <td> {{item.EmpName}}</td>
        <td>{{item.EMPCode}}</td>
        <td> {{item.Salary}}</td>
        <td>{{item.Email}}</td>

    </tr>

</table>

app.component.ts

in app.component we have created the method to call the service . and initiated the service in constructor .

import { Component } from '@angular/core';
import {EmpserviceServicefrom './empservice.service'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'MyService';
EmpServiceresponse : any ;

  constructor(private _EmpserviceService:EmpserviceService ){}
GetEmpDetails(){

  this._EmpserviceService.GetEmployeDetails().subscribe((respp)=>
  {
    this.EmpServiceresponse = respp;
    console.log(this.EmpServiceresponse);

  })
}
}

empentities.ts

This is the Entities in which data will be mapped.

export class Empentities {

    EMPCodestring;
    EmpNamestring;
    Emailstring;
    Salary : number;
}

empservice.service.ts

we have created this service by below command 

ng g service Empservice

once service is created then we will provide API url and call it in a method and provide its return type as JSON

import { Injectable } from '@angular/core';
import { HttpClient , HttpResponseHttpHeaders } from '@angular/common/http';  
import { Empentities } from './model/empentities';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class EmpserviceService {
  
 url = 'http://localhost:37187/Api/ViewContact/';  

  constructor(private http:HttpClient) { }

  GetEmployeDetails(): Observable<Empentities[]> {  
    
    return this.http.post<Empentities[]>(this.url+'/ViewEmpDetails'
    {headers:new HttpHeaders({'Content-Type':'application/json'})});
  }  

}

app.module.ts

In App.module we will register our service and add the HttpClientModule Module in Import array .

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
import { EmpserviceService } from './empservice.service';

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


output

click on Button you will get the reponse 

Right click chosse inpect Element  and see the response on Console


Follow us :   Shubh Techno Expert on Youtube 

Monday, December 9, 2019

session storage and local storage in Angular

How to access Local and Session variable in Angular


To Set Value in Session storage

Sessionstorage.SetItem('key','value')

To get Value from Session storage

Sessionstorage.getitem('key')

To set Value in Local storage

localstorage.SetItem('key','value')

To get Value from Local storage

sessionstorage.getitem('key')

How to Clear Session variable

sessionstorage.clear()

How to remove all session items .

sessionstorage.removeitem('key')

local storage works like Viewstate and session storage work like session variable .

http://xafdeveloper.blogspot.com

https://youtu.be/povG03z340E

Saturday, November 30, 2019

Web Config file for Angular App



Web Config File for Angular App

when you release Angular app on production then web.config file is needed for URL Rewriting .
you can add a text file and change it file type as configuration web.config

web.Config

<?xml version="1.0" encoding="utf-8"?>
<configuration>

<system.webServer>
  <rewrite>
    <rules>
      <rule name="Routes" stopProcessing="true">
        <match url=".*" />
        <conditions logicalGrouping="MatchAll">
          <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
         </conditions>
        <action type="Rewrite" url="/eportal">
      </rule>
    </rules>
  </rewrite>
</system.webServer>
</configuration>

Note : if you are running IIS 10 then remove   <match url=".*" />  as <match url="." />


@ShubhTechnoExpet on Facebook page .

Build Angular app for Production


Build Angular App for Production


while you plan for production release then keep these things in Mind

ng build --prod --base--href /vdname/

above command will create a production build in your app folder . a dist folder will be added in your app folder with name "dist".

This dist folder will have all build files .

Note1 : keep in mind that vdname and your actual vd name where you will do the deployment always                   will be the same .
suppose your hosting address is http://www.xafdeveloper.blogspot.com
then while making build you need to create build like this .

ng build --prod --base--href   /xafdeveloper/

Note2: URL Rewrite extension need to install in IIS and you can download it from Microsoft site .

Note3: you need to add web.config file in your vd as by default angular build didn't create a                                   "web.config" file .

you can create is by adding a text file and change its name and file type as config .
now copy url rewrite code from web and paste it in this file .
Now access your app and enjoy Angular Application Cheers !..
Note3. you can see base reference details in Index.html file also in your build folder


@ShubhTechnoExpet on Facebook page .