Pages

CRUD Operation on Angular

Now, we add a class model with shared folder with the following command.

ng g class shared/customer --type=model

Add property to the customer.model.ts

export class Customer {
    id:number= 0;
    name!: string;
    lastName:string='';
    email:string = '';
    age!:number;
    gender:string='Male';
    isActive!:number;
}

Add Services and Components

Services

Now, add service which will communicate with Web API inside shared folder.

ng g s shared/customer



Components

Now, add customer-details components

ng g c customer-details


Now, add customer-form components

ng g c customer-form


Note:

g - generate

c - component

s - service


Add Bootstrap

Now, go to https://getbootstrap.com/docs/4.0/getting-started/introduction/ and copy the plugin of java script and CSS in index.html


Register the created module

Now, we open app.module.ts to register services and module. In app.module, we have all the components has been auto added. But, we need to add service so we can use them in our angular app. Also we need to add HTTP module.



Adding services and components code:-

service
Now, Open customer.service.ts file and add code.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Customer } from './customer.model';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})

export class CustomerService {

  constructor(private myhttp:HttpClient) { }
  customerUrl:string ='https://localhost:44395/api/Customer/TblCustomer';
 
  customerPostUrl:string ='https://localhost:44395/api/Customer/PostCustomer';

  customerDeleteUrl = 'https://localhost:44395/api/Customer/DeleteCustomer';
 
  customerPutUrl = 'https://localhost:44395/api/Customer/UpdateCus';

 
  listCustomer : Customer[]=[];

  customerdata:Customer=new Customer(); //for post data // insert data
 
  saveCustomer()
  {
    // console.log("postapi",this.employeePostUrl);
    return this.myhttp.post(this.customerPostUrl,this.customerdata);
  }
  updateCustomer()
  {
   
    return this.myhttp.post(this.customerPutUrl,this.customerdata);
  }
  getCustomer(): Observable<Customer[]>
  {
    return this.myhttp.get<Customer[]>(this.customerUrl);
  }
  deleteCustomer(id:number)
  {
    return this.myhttp.delete(`${this.customerDeleteUrl}/${id}`);
  }
}

Now, Open customer-details.component.ts file and add code.


import { Component, OnInit } from '@angular/core';
import { Customer } from '../shared/customer.model';
import { CustomerService } from '../shared/customer.service';

@Component({
  selector: 'app-customer-details',
  templateUrl: './customer-details.component.html',
  styleUrls: ['./customer-details.component.css']
})
export class CustomerDetailsComponent implements OnInit {
constructor(public custService:CustomerService) { }
ngOnInit() {
  this.custService.getCustomer().subscribe(data=>{
    this.custService.listCustomer=data
  });
}
populateCustomer(selectedCustomer:Customer)
{
  this.custService.customerdata=selectedCustomer;
}
delete(id:number)
{
  if(confirm('Are you really want to delete this record?'))
  {
    this.custService.deleteCustomer(id).subscribe(data=>{
      console.log('Record delete');

      this.custService.getCustomer().subscribe(data=>{
        this.custService.listCustomer=data
      });
    },
    err=>{
      console.log('Error not deleted');
    });
  }
}
}

Components (customer-detail)

Now, Open the app.component.html and add app-customer-details selector 

Now, Open the customer-detail.component.html and add code.


<div class="container">
    <app-customer-form></app-customer-form>
    </div>
    <table class="table table-hover">
        <thead class="thead-dark">
            <tr>
                <th>Name</th>
                <th>Last Name</th>
                <th>Email</th>
                <th>Age</th>
                <th>Gender</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <tr *ngFor="let cust of custService.listCustomer">
                <td>{{cust.name}}</td>
                <td>{{cust.lastName}}</td>
                <td>{{cust.email}}</td>
                <td>{{cust.age}}</td>
                <td>{{cust.gender}}</td>
                <td>
                    <div class="dropdown">
                        <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                          Action
                        </button>
                        <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
                          <a class="dropdown-item" href="#" (click)="populateCustomer(cust)">Edit</a>
                          <a class="dropdown-item" href="#" (click)="delete(cust.id)">Delete</a>
                        </div>
                      </div>
                </td>
            </tr>
        </tbody>
    </table>
   
   


Now, Open customer-form.component.ts file and add code.

import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Customer } from '../shared/customer.model';
import { CustomerService } from '../shared/customer.service';

@Component({
  selector: 'app-customer-form',
  templateUrl: './customer-form.component.html',
  styleUrls: ['./customer-form.component.css']
})


export class CustomerFormComponent {
  constructor(public custService: CustomerService) { }

  submit(form: NgForm) {
    this.custService.customerdata.isActive = form.value.isActive == true ? 1 : 0;

    if (this.custService.customerdata.id == 0) {
      this.insertCustomer(form);
    }
    else {
      this.updateCustomer(form);
    }

  }

  insertCustomer(myForm: NgForm) {
    this.custService.saveCustomer().subscribe(d => {
      this.resetForm(myForm);
      this.refreshData(myForm);
      console.log('saved success');
    });
  }

  updateCustomer(myForm: NgForm) {
    this.custService.updateCustomer().subscribe(d => {
      this.resetForm(myForm);
      this.refreshData(myForm);
      console.log('update success');
    })
  }

  resetForm(myForm: NgForm) {
    myForm.form.reset();
    this.custService.customerdata = new Customer();
  }

  refreshData(myForm: NgForm) {
    this.custService.getCustomer().subscribe(res => {
      this.custService.listCustomer = res;
    });
  }
}

Component(customer-form)
Now, Open the customer-detail.component.html and add app-customer-form selector

<div class="container">
    <app-customer-form></app-customer-form>
    </div>


Now, Open the customer-form.component.html and add code.





<input #checkbox1 type="checkbox" name="toggle" id="toggle">
<label for="toggle"></label>

<div class="container">
</div>
<div class="formAdd">
<form autocomplete="off" #myForm="ngForm" (ngSubmit)="myForm.form.valid && submit(myForm)">
    <div class="container">
        <div class="row">
            <div class="col-md-3">
                <input type="hidden" name="id" [value]="custService.customerdata.id">
                <label for="name">Name</label>
                <input type="text" class="form-control" name="name" placeholder="name" #name="ngModel" [(ngModel)] ="custService.customerdata.name">
            </div>
            <div class="col-md-3">
                <label for="lastname">Last Name</label>
                <input type="text" class="form-control" name="lastname" placeholder="lastname" #lastname="ngModel" [(ngModel)] ="custService.customerdata.lastName">
            </div>
            <div class="col-md-3">
                <label for="email">Email</label>
                <input type="email" class="form-control" name="email" placeholder="email" #email="ngModel" [(ngModel)] ="custService.customerdata.email">
            </div>
            <div class="col-md-3">
                <label for="age">Age</label>
                <input type="number" class="form-control" name="age" placeholder="age" #age="ngModel" [(ngModel)] ="custService.customerdata.age">
            </div>
        </div>
            <div class="row mt-2">
            <div class="col-md-6">
                <label for="gender">Gender</label>
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-check-inline">
                            <label class="form-check-label">
                              <input type="radio"  class="form-check-input" name="gender" #gender="ngModel" [(ngModel)]="custService.customerdata.gender" value="Male">Male
                            </label>
                          </div>
                          <div class="form-check-inline">
                            <label class="form-check-label">
                                <input type="radio" class="form-check-input" name="gender" #gender="ngModel" [(ngModel)]="custService.customerdata.gender" value="female">Female
                            </label>
                          </div>
                    </div>
                </div>
            </div>
            </div>
     
        <div class="row">
            <div class="col-md-10"></div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-Success">Save</button>
            </div>
        </div>
    </div>
</form>
</div>





Now, add CSS to the customer-form.component.css

.formAdd {
    background:#c7b29e;
    color:#FFF;
    position: absolute;
    top: -250px;
    left: 0;
    width: 100%;
    height: 250px;
    padding: 20px;
    transition: top 300ms cubic-bezier(0.17, 0.04, 0.03, 0.94);
    overflow: hidden;
    box-sizing: border-box;
     
    }
   
    #toggle {
      position:absolute;
      appearance:none;
      cursor:pointer;
      left:-100%;
      top:-100%;
    }
   
    #toggle + label {
      position:absolute;
      cursor:pointer;
      padding:10px;
      background: #26ae90;
    width: 100px;
    border-radius: 3px;
    padding: 8px 10px;
    color: #FFF;
    line-height:20px;
    font-size:12px;
    text-align:center;
    -webkit-font-smoothing: antialiased;
    cursor: pointer;
      margin:20px 50px;
      transition:all 500ms ease;
    }
    #toggle + label:after {
      content:"Add New"
    }
   
    .container {
    transition: margin 300ms cubic-bezier(0.17, 0.04, 0.03, 0.94);
      padding:2em 3em;
    }
   
    #toggle:checked ~ .formAdd {
      top: 0;
    }
   
    #toggle:checked ~ .container {
      margin-top: 250px;
    }
   
    #toggle:checked + label {
      background:#dd6149;
    }
   
    #toggle:checked + label:after {
      content:"Close"
    }

Now, run the project using the following command 

"ng serve -o" or "ng serve --open"


Customer Details




Add Customer



Edit Customer



Customer detail after editing





Delete Customer




Customer detail after deletion












No comments:

Post a Comment

Make new Model/Controller/Migration in Laravel

  In this article, we have included steps to create a model and controller or resource controller with the help of command line(CLI). Here w...