19 April 2020

Service example in angular


  • Open Command prompt and use below commands to create angular project
  • E:
  • cd E:\TestProjects\Angular
  • ng new service-example-in-angular --style=scss --routing --skip-install
  • cd service-example-in-angular
  • npm install
  • Open project in visual studio code.
  • Go to App folder then right click on app folder click on Generate Service like below image.

  • Then enter service name as below image. in my case "student" is module name.

  • Then click on enter. it will create student service (student.service.ts and other files) as below image.

  • Now create Student components in app folder.
  • Update student.service.ts file as below.

  • import { Injectable } from '@angular/core';

    @Injectable({
      providedIn: 'root'
    })
    export class StudentService {

      getStudentsList(): any[]
      {
        var StudentsList = [
          {Id:101Name: "Adi"Email:"jc.adi101@gmail.com" },
          {Id:102Name: "Pavan"Email:"pavan@gmail.com"},
          {Id:103Name: "Nani"Email:"Nani@gmail.com" },
          {Id:104Name: "Madhan"Email:"Madhan@gmail.com" }
        ];
        return StudentsList;
      }
    }
  • Update student.component.ts file as below.

  • import { ComponentOnInit } from '@angular/core';
    import { StudentService } from '../student.service';


    @Component({
      selector: 'app-student',
      templateUrl: './student.component.html',
      styleUrls: ['./student.component.css']
    })
    export class StudentComponent implements OnInit {
      StudentsList = [];
      constructor(private studentServiceStudentService )
      {
      }
      ngOnInit() {
        this.StudentsList = this.studentService.getStudentsList();
      }
    }
  • Update student.component.html file as below.

  • <table>
      <tr>
        <th>Id</th>
        <th>Name</th>
        <th>Email</th>
      </tr>
      <tr *ngFor="let student of StudentsList">
        <td>
          {{student.Id}}
        </td>
        <td>
          {{student.Name}}
        </td>
        <td>
          {{student.Email}}
        </td>
      </tr>

    </table>
  • Update app.component.html file as below.

  • <h1>Service example in angular</h1>
    <app-student></app-student>

    Output:


    Service in angular

    Service: Service is a class, witch is collection of properties and methods, witch contain re-usable programming logic , witch mainly contains Data source interaction (API Call) and business logic.


    • Services can be accessible in components, directives or pipes.
    • Services can be accessible from other Services.
    Steps to create Service:
    • Create Service class
      • Create a class with one or more properties and methods that contains business logic and data access logic.
    • Make ready the service for dependency injection:
      • Add @Injectable() decorator above the service class.
    • Provide the service globally/locally: we have 4 below methods
      • Add the provideIn:"root" option in @Injectable() decorator.
      • Add provides:[service] in AppModule's metadata.
      • Add provides:[service] in any other module's metadata.
      • Add provides:[service] in any other component's metadata.
    • Inject the service into actual component:
      • Add @Inject(service) private referenceVariale : Service in any  component's constructor.

    18 April 2020

    module example in angular

  • Open Command prompt and use below commands to create angular project
  • E:
  • cd E:\TestProjects\Angular
  • ng new module-example-in-angular --style=scss --routing --skip-install
  • cd module-example-in-angular
  • npm install
  • Open project in visual studio code.
  • Go to App folder then right click on app folder click on Generate Module like below image.

    • Then enter module name as below image. in my case "admin" is module name.

    • Then click on enter. it will create admin module (admin folder, admin.module.ts file and other files) as below image.
    • Now create Home, Dashboard and User components in Admin module. Created components we can see like below image in admin folder.
    • Home, Dashboard and User components are imported into Admin.module.ts file like below code. if we want to use Admin module components (like Home, Dashboard, User) in other modules like App.module.ts we need to export those components from admin module like below code. in below code we are exporting Home and Dashboard components  to outside modules.
    import { NgModule } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { AdminComponent } from './admin.component';

    import {DashboardComponentfrom './dashboard/dashboard.component'
    import {HomeComponentfrom './home/home.component'
    import {UserComponentfrom './user/user.component'

    @NgModule({
      declarations: [
        AdminComponent,
        DashboardComponent,
        HomeComponent,
        UserComponent
     ],
      imports: [
        CommonModule
      ],
      exports:[
        DashboardComponent,
        HomeComponent
      ]
    })
    export class AdminModule { }
    • In below code we can see how to import admin module in app module.
    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';

    import { AppRoutingModule } from './app-routing.module';
    import { AppComponent } from './app.component';
    import { LoginComponent } from './login/login.component';
    import{AdminModulefrom './admin/admin.module';

    @NgModule({
       declarations: [
          AppComponent,
          LoginComponent
       ],
       imports: [
          BrowserModule,
          AppRoutingModule,
          AdminModule
       ],
       exports: [],
       providers: [],
       bootstrap: [
          AppComponent
       ]
    })
    export class AppModule { }
    • Now we can use Dashboard, Home components in app.components.html like below code, but user component not possible to use. reason we didn't exported user component in admin.module.ts
    <h1>module example in angular</h1>

    <app-dashboard></app-dashboard>
    <app-home></app-home>

    Output:




    Angular Module

             
       In Angular, a module is a mechanism to group components, directives, pipes and services that are related, in such a way that can be combined with other modules to create an application.In case you are developing a shopping  website Admin, User, Employee, Guest and Service provider become part of a module.

    To define module, we can use the NgModule. When you create a new project using the Angular CLI command, the ngmodule is created in the app.module.ts file by default and it looks as follows.

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';

    import { AppRoutingModule } from './app-routing.module';
    import { AppComponent } from './app.component';

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

    Declaration:
    Declaration is one part in Module. It is an array of components created by user. If any new component gets created by user, it will be imported first and the reference will be included in declarations as shown below

      declarations: [
        AppComponent
      ]

    Imports:
    Imports is one part in Module. it is an array of modules required to be used in the application. It can also be used by the components in the Declaration array. For example, right now in the @NgModule we see the Browser Module and AppRouting Module imported. it will look like below.

      imports: [
        BrowserModule,
        AppRoutingModule
      ]

    Providers:
    This will include the services created.

    Bootstrap:
    This includes the main app component for starting the execution. it will look like below. in below code AppComponent is the starting componet for this module.

      bootstrap: [AppComponent]

    17 April 2020

    ngSwitch example in angular


  • Open Command prompt and use below commands to create angular project
  • E:
  • cd E:\TestProjects\Angular
  • ng new ngSwitch-example-in-angular --style=scss --routing --skip-install
  • cd ngSwitch-example-in-angular
  • npm install
  • Open project in visual studio code.
  • Open app.component.ts file and update code as below

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

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

  • Open app.component.html file and update code as below


  • <h1>ngSwitch example in angular</h1>

    <ul [ngSwitch]="animals">
      <li *ngSwitchCase="'Tiger'">Tiger</li>
      <li *ngSwitchCase="'Dog'">Dog</li>
      <li *ngSwitchCase="'Cat'">Cat</li>
      <li *ngSwitchCase="'Lion'">Lion</li>
      <li *ngSwitchCase="'Elephant'">Elephant</li>
      <li *ngSwitchDefault>cow</li>
    </ul>


    Output:


    Built-in Pipes example in angular


  • Open Command prompt and use below commands to create angular project
  • E:
  • cd E:\TestProjects\Angular
  • ng new Built-in-Pipes-example-in-angular --style=scss --routing --skip-install
  • cd Built-in-Pipes-example-in-angular
  • npm install
  • Open project in visual studio code.
  • Open app.component.ts file and update code as below

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

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.scss']
    })
    export class AppComponent {
    title = 'Built-in Pipes example in angular';  
    todaydate = new Date();  
    jsonval = {name: 'Adi'age: '29'address:{a1: 'Anantapur'a2: 'AP'}};  
    months = ['Jan''Feb''Mar''April''May''Jun',  
      'July''Aug''Sept''Oct''Nov''Dec'];  
    }
  • Open app.component.ts file and update code as below


  • <h1>Built-in Pipes example in angular</h1>
    <h4><u>Uppercase Pipe</u></h4>    
    <p>{{title | uppercase}}</p> 
    <h4><u>Lowercase Pipe</u></h4>    
    <p>{{title | lowercase}}</p>  
    <h4><u>Currency Pipe</u></h4>    
    <p>{{5889.23 | currency:"USD"}}</p>
    <p>{{5889.23 | currency:"USD":true}}</p> 
    <h4><u>Date pipe</u></h4>    
    <p>{{todaydate | date:'d/M/y'}}</p>
    <p>{{todaydate | date:'shortTime'}}</p>  
    <h4><u>Decimal Pipe</u></h4>    
    <p>{{ 754.98787814 | number: '3.4-4' }}</p>
    <h4><u>Json Pipe</u></h4>    
    <p>{{ jsonval | json }}</p>  
    <h4><u>Percent Pipe</u></h4>    
    <p>{{00.84565 | percent}}</p>  
    <h4><u>Slice Pipe</u></h4>    
    <p>{{months | slice:3:6}}</p>  

    Output:

    Date format pipe example in angular

  • Open Command prompt and use below commands to create angular project
  • E:
  • cd E:\TestProjects\Angular
  • ng new Date-format-pipe-example-in-angular --style=scss --routing --skip-install
  • cd Date-format-pipe-example-in-angular
  • npm install
  • Open project in visual studio code.
  • Open app.component.ts file and update code as below

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

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.scss']
    })
    export class AppComponent {
      todayDate : Date = new Date();
    }
  • Open app.component.html file and update code as below

  • <h1>Date format pipe example in angular</h1>

    <p><b>M/d/yy, h:mm a:</b>{{todayDate | date:'short'}}</p>
    <p><b>MMM d, y, h:mm:ss a:</b>{{todayDate | date:'medium'}}</p>
    <p><b>MMMM d, y, h:mm:ss a z:</b>{{todayDate | date:'long'}}</p>
    <p><b>EEEE, MMMM d, y, h:mm:ss a zzzz:</b>{{todayDate | date:'full'}}</p>
    <p><b>M/d/yy:</b>{{todayDate | date:'shortDate'}}</p>
    <p><b>MMM d, y:</b>{{todayDate | date:'mediumDate'}}</p>
    <p><b>MMMM d, y:</b>{{todayDate | date:'longDate'}}</p>
    <p><b>EEEE, MMMM d, y:</b>{{todayDate | date:'fullDate'}}</p>
    <p><b>h:mm a:</b>{{todayDate | date:'shortTime'}}</p>
    <p><b>h:mm:ss a:</b>{{todayDate | date:'mediumTime'}}</p>
    <p><b>h:mm:ss a z:</b>{{todayDate | date:'longTime'}}</p>
    <p><b>h:mm:ss a zzzz:</b>{{todayDate | date:'fullTime'}}</p>
    Output:


    ng-template example in angular

  • Open Command prompt and use below commands to create angular project
  • E:
  • cd E:\TestProjects\Angular
  • ng new ng-template-example-in-angular --style=scss --routing --skip-install
  • cd ng-template-example-in-angular
  • npm install
  • Open project in visual studio code.
  • Open app.component.ts file and update code as below

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

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.scss']
    })
    export class AppComponent {
      isValid:boolean=true;
    }
  • Open app.component.ts file and update code as below


  • <h1>ng-template example in angular</h1>
    <B>Using If with Else</B>
    <div *ngIf="isValid; else templateName">
      If isValid is true
    </div>
    <ng-template #templateName>
      If isValid is false
    </ng-template>
    <br/>
    <B>Using If with Then</B>
    <div>
    <div *ngIf="isValid; then templateName1">
      Here is never showing
    </div>
    <ng-template #templateName1>
      If isValid is true
    </ng-template>
    </div>
    <br/>
    <B>Using If with Then and Else</B>
    <div>
    <div *ngIf="isValid; then thenTemplateName1 else elseTemplateName1">
      Here is never showing
    </div>
    <ng-template #thenTemplateName1>
      If isValid is true
    </ng-template>
    <ng-template #elseTemplateName1>
      If isValid is false
    </ng-template>
    </div>


    Output:



    ngIf-else example in angular

  • Open Command prompt and use below commands to create angular project
  • E:
  • cd E:\TestProjects\Angular
  • ng new ngIf-else-example-in-angular --style=scss --routing --skip-install
  • cd ngIf-else-example-in-angular
  • npm install
  • Open project in visual studio code.
  • Open app.component.ts file and update code as below

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

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.scss']
    })
    export class AppComponent {
      isValid:boolean=true;
    }
  • Open app.component.html file and update code as below
  • <h1>ngIf-else example in angular</h1>
    <B>Using If with Else</B>
    <div *ngIf="isValid; else templateName">
      If isValid is true
    </div>
    <ng-template #templateName>
      If isValid is false
    </ng-template>
    <br/>
    <B>Using If with Then</B>
    <div>
    <div *ngIf="isValid; then templateName1">
      Here is never showing
    </div>
    <ng-template #templateName1>
      If isValid is true
    </ng-template>
    </div>
    <br/>
    <B>Using If with Then and Else</B>
    <div>
    <div *ngIf="isValid; then thenTemplateName1 else elseTemplateName1">
      Here is never showing
    </div>
    <ng-template #thenTemplateName1>
      If isValid is true
    </ng-template>
    <ng-template #elseTemplateName1>
      If isValid is false
    </ng-template>
    </div>

    Output:

    ngIf example in angular

  • Open Command prompt and use below commands to create angular project
  • E:
  • cd E:\TestProjects\Angular
  • ng new ngIf-example-in-angular --style=scss --routing --skip-install
  • cd ngIf-example-in-angular
  • npm install
  • Open project in visual studio code.
  • Open app.component.ts file and update code as below

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

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.scss']
    })
    export class AppComponent {
      isValid = true;
      numbers = [1,2,3,4,5,6,7,8,9,10]; 
    }
  • Open app.component.ts file and update code as below

  • <h1>ngIf example in angular</h1>
    <p *ngIf="isValid">
      Data is valid.
    </p>
    <p *ngIf="!isValid">
      Data is not valid.
    </p>

    <div *ngFor="let id of numbers">
      <div *ngIf="id%2 == 0">
      <div>{{id}}-Even Number</div>
      </div>  
      <div *ngIf="id%2 == 1">
      <div>{{id}}-Odd Number</div>
      </div>  
    </div>

    Output: