Wednesday, 7 April 2021

Crud Operation on Static Data

 Step1: Create a service in angular with some static data array. as following

public getUser(){    

 return [       

{id: 1,firstName: 'Frank', lastName: 'Murphy', email:'frank.murphy@test.com', role: 'User'},       

{id: 2,firstName: 'Vic', lastName: 'Reynolds', email:'vic.reynolds@test.com', role: 'Admin'},    

 {id: 3,firstName: 'Gina', lastName: 'Jabowski', email:'gina.jabowski@test.com', role: 'Admin'},   

 {id: 4,firstName: 'Jessi', lastName: 'Glaser', email:'jessi.glaser@test.com', role: 'User'},       

{id: 5,firstName: 'Jay', lastName: 'Bilzerian', email:'jay.bilzerian@test.com', role: 'User'},   

  ]   } 

Step2: Create User.model.ts file to define all properties

export class User {     

constructor (         public id?: number,         public  firstName?: string,         public lastName?: string,         public email?: string,         public role?: string,     ){} 

}


Step3: Generate User component & write following code in User.component.ts

import { ComponentEventEmitterOnInitOutput } from '@angular/core';
import { NgForm } from '@angular/forms';
import { ActivatedRouteRouter } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { User } from '../User.model';
import { UserdataService } from '../userdata.service';


@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
  userUser = new User();
  public id;
  public firstName;
  public lastName;
  public email;
  public role;
public Users = [];
  constructorprivate serviceUserdataService
    private routerRouter
    private routeActivatedRoute
    private toastrToastrService ) { }


  ngOnInit(): void {
   this.Users = this.service.getUser();
  }


  public addUser(fromNgForm) {
    var Id = this.service.getUser().filter(x=>x.id == this.id)
    if(this.user.id == null || this.user.id == 0){
  let userId = this.Users.length + 1;
  this.user.id = userId;
  this.Users.push(this.user);
  this.user = new User();
  this.toastr.success('User added Successfully','User Record');
    } else {
      let userIndex = this.Users.findIndex(x=>x.id == this.user.id)
      this.Users.splice(userIndex,1,this.user);
      this.user = new User();
      this.toastr.success('User updated Successfully','User Record')
    }
  }
  updateUser(idnumber){
    let Id = this.Users.find(x=>x.id == id);
   this.user.id = id;
   this.user.firstName = Id.firstName;
    this.user.lastName = Id.lastName;
    this.user.email =Id.email;
    this.user.role = Id.role;
  }
  
  deleteUser(inumber) {
    var status = confirm('Are You sure to delete the record?');
    if(status == true) {
      let userId = this.Users.findIndex(x=>x.id ==i)
      this.Users.splice(userId,1);
      this.toastr.warning('User deleted successfully','User Record');
    }
  }
 public getDetails(item){
    this.router.navigate(['details'item.id], {relativeTo:this.route})
  }


  resetAll(){
    this.user.id = null;
    this.user.firstName = '',
    this.user.lastName = '',
    this.user.email = '',
    this.user.role = ''
    this.toastr.info('Data reset');
  }
}

Step4: Write following code in User.component.html

<nav style="justify-content: center; font-size: large;" class="navbar navbar-expand-sm bg-primary navbar-dark">
    Crud Operation 
  </nav>
  <div class="container">
    <div class="adduser">
      <form #form="ngForm" (ngSubmit)="addUser(form)">
        <div class="row">
          <div class="col-md-6">
            <input type="hidden" name="id" [(ngModel)]="user.id">
            <div class="form-group">
              <label>First Name</label>
              <input type="text" name="firstName" [(ngModel)]="user.firstName" class="form-control">
            </div>
            <div class="form-group">
              <label>Email</label>
              <input type="text" name="email" [(ngModel)]="user.email" class="form-control">
            </div>
          </div>
          <div class="col-md-6">
            <div class="form-group">
              <label>Last Name</label>
              <input type="text" name="lastName" [(ngModel)]="user.lastName" class="form-control">
            </div>
            
            <div class="form-group">
              <label>Role</label>
              <input type="text" name="role" [(ngModel)]="user.role" class="form-control">
            </div>
          </div>
          </div>
          <div class="form-group">
            <button class="btn btn-success"  type="submit" style="width: 300px; height: 40px; margin-right: 2px;" >Add</button>
            <button class="btn btn-info" (click)="resetAll()"  type="button" style="width: 300px; height: 40px; margin-right: 2px;" >Reset</button>
          </div>
      </form>
    </div>
    <hr>
    <label>List Of Users</label>
      <table class="table table-striped table-bordered">
          <thead>
              <tr>
                <th>Id</th>
                  <th>Name</th>
                  <th>Email</th>
                  <th>Role</th>
                  <th style="text-align: center;">Actions</th>
              </tr>
          </thead>
          <tbody>
              <tr *ngFor="let user of Users; let i= index">
                <td>{{i+1}}</td>
                  <td>{{user.firstName}} {{user.lastName}}</td>
                  <td>{{user.email}}</td>
                  <td>{{user.role}}</td>
                  <td style="text-align: center;">
                    <button style="margin-right: 4px;" class="btn btn-primary" (click)="updateUser(user.id)" >Edit</button>
                    <button style="margin-right: 4px;" class="btn btn-danger" (click)="deleteUser(user.id)">Delete</button>
                    <button class="btn btn-primary" (click)="getDetails(user)" >View Details</button>
                  </td>
              </tr>
          </tbody>
      </table>
  </div>
  
Step5: Generate Details component & write following code in .ts file
import { ComponentOnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { UserdataService } from '../userdata.service';

@Component({
  selector: 'app-details',
  templateUrl: './details.component.html',
  styleUrls: ['./details.component.css']
})
export class DetailsComponent implements OnInit {
  public userId;
  public Users = [];
  constructor(private serviceUserdataServiceprivate routeActivatedRoute) { }
  
  ngOnInit(): void {
    this.userId = this.route.snapshot.paramMap.get('id');
    this.Users = this.service.getUser().filter(x=>x.id == this.userId);
  }

}

Step6: Write following code in .html file
<p>Details of Users</p>
<table class="table table-hover" border="1px">
    <tr>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Email</th>
        <th>Role</th>
    </tr>
    <tr>
        
        <td>{{Users[0].firstName}}</td>
        <td>{{Users[0].lastName}}</td>
        <td>{{Users[0].email}}</td>
        <td>{{Users[0].role}}</td>
    </tr>
</table>
<a [routerLink]="['']">Back To List</a>

Step7: For Bootstrap use npm install bootstarp & register it in style.css

Our application will look as following

When User Clicks on ViewDetails button , It will navigate to another component which shows
all details of user selected



PostedBy:pankaj_bhakre