CRUD Operation Using Prime NG

In This artical I will Explain How can create Registration form using PrimeNg Control and CRUD operation.

Step1: Create a New Angular Application.

ng new demo

Step2: Create Component.

ng g c registration

Step3: Now, install the primeNG in your application.

Please follow this How to install primeNG https://www.thecodehubs.com/how-to-setup-primeng-in-angular/

Step4: import below primeNG Module in your app.module.ts

import { NgModule,CUSTOM_ELEMENTS_SCHEMA  } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AutoCompleteModule } from 'primeng/autocomplete';
import { CheckboxModule } from 'primeng/checkbox';
import { DropdownModule } from 'primeng/dropdown';
import { FormsModule } from '@angular/forms';
import { InputTextModule } from 'primeng/inputtext';
import { InputNumberModule } from 'primeng/inputnumber';
import { RadioButtonModule } from 'primeng/radiobutton';
import { ButtonModule } from 'primeng/button';
import { TableModule } from 'primeng/table';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { LoginComponent } from './login/login.component';
import { RegistrationComponent } from './registration/registration.component';
import { ControlsComponent } from './controls/controls.component';
import { ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { TockeninterceptorService } from './tockeninterceptor.service';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { FileUploadModule } from 'primeng/fileupload';
import { PasswordModule } from 'primeng/password';
import { CalendarModule } from 'primeng/calendar';
import { DialogModule } from 'primeng/dialog';
import { DatePipe } from '@angular/common';
import { ConfirmationService } from 'primeng/api';
import {ConfirmDialogModule} from 'primeng/confirmdialog';


@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    RegistrationComponent,
    ControlsComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    AutoCompleteModule,
    CheckboxModule,
    DropdownModule,
    FormsModule,
    InputTextModule,
    InputNumberModule,
    RadioButtonModule,
    ButtonModule,
    TableModule,
    BrowserAnimationsModule,
    ReactiveFormsModule,
    HttpClientModule,
    FileUploadModule,
    PasswordModule,
    CalendarModule,
    DialogModule,
    ConfirmDialogModule
  ],
  providers: [{provide:HTTP_INTERCEPTORS,useClass:TockeninterceptorService,multi:true},DatePipe,ConfirmationService],
  bootstrap: [AppComponent],
  schemas:
        [CUSTOM_ELEMENTS_SCHEMA]
})
export class AppModule { }

Step5: Write the below code to your registration.component.ts

import { Component, OnInit } from '@angular/core';
import { Employee_Mst } from '../Employee_Mst';
import { EmployeeService } from '../employee.service';
import { FormGroup,FormBuilder, Validators,FormArray,FormControl} from '@angular/forms';
import { Country } from '../Country';
import { City } from '../City';
import { ConfirmationService } from 'primeng/api';

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

export class RegistrationComponent implements OnInit {
  hobbiesarr: any = [];
  visible: boolean = false;
  employeeTitle: any;
  Employee_Mst: Employee_Mst[] = [];
  employeeForm!: FormGroup;
  fDate: any;
  profileImage: any;
  Imageloaded: boolean = false;
  hobbiesarray!: FormArray;
  country: Country[] = [];
  city: City[] = [];
  hobbieCheckbox: boolean = true;
  document: [] = [];
  date: any;
  submitted = false;
  checkConfirmPassword:string = "";
  Hobbies = [
    { name: 'reading', value: 'Reading', selected: false },
    { name: 'writting', value: 'Writting', selected: false },
    { name: 'travelling', value: 'Travelling', selected: false },
  ];

  constructor(
    private _employeeService: EmployeeService,
    private _fb: FormBuilder,
    private _confirmationService: ConfirmationService
  ) {}

  ngOnInit(): void {
    this.employeeForm = this._fb.group(
      {
        Id: [''],
        Name: ['',[Validators.required]],
        DOB: [new Date()],
        Gender: ['', [Validators.required]],
        PhoneNo: ['',[Validators.required]],
        Address: ['',[Validators.required]],
        EmailId: ['',[Validators.required]],
        Designation: ['', [Validators.required]],
        Hobbie: this._fb.array([]),
        Salary: ['',[Validators.required]],
        Country: ['', [Validators.required]],
        City: ['', [Validators.required]],
        Image: [''],
        Password: ['',Validators.compose([Validators.required, Validators.minLength(6)]),],
        ConfirmPassword: ['',Validators.compose([Validators.required, Validators.minLength(6)])],
      },
      {
        validator: this.Conformvalidation('Password', 'ConfirmPassword'),
      }
    );
    this.getAllEmployee();
    this.getCountryData();
  }

  Conformvalidation(Password: string, ConfirmPassword: string) {
    return (group: FormGroup): { [key: string]: any } => {
      let password = group.controls[Password];
      let confirmpassword = group.controls[ConfirmPassword];
      if (password.value != confirmpassword.value) {
        this.checkConfirmPassword = "Password and ConfirmPassword do not match!";
        return {
          result: 'Password and ConfirmPassword do not match!',
        };
      }
      else{
        this.checkConfirmPassword = "";
      }
      return {};
    };
  }

  getAllEmployee() {
    this._employeeService.getEmployee().subscribe((employee) => {
      this.Employee_Mst = employee;
    });
  }

  getCountryData(): void {
    this._employeeService.getCountry().subscribe((country) => {
      this.country = country;
    });
  }

  onSubmit() {
    this.submitted = true;
    var employeeid = this.employeeForm.value.Id;
    if (!employeeid) {
      if(!this.employeeForm.invalid){
        this.hobbiesarray.controls.forEach((item: any, FormControl) => {
          this.hobbiesarr.push(item.value);
        });
        this.employeeForm.value;
        const employee_Mst = new Employee_Mst();
        employee_Mst.name = this.employeeForm.value.Name;
        employee_Mst.dob = this.employeeForm.value.DOB;
        employee_Mst.gender = this.employeeForm.value.Gender;
        employee_Mst.phoneNo = this.employeeForm.value.PhoneNo.toString();
        employee_Mst.address = this.employeeForm.value.Address;
        employee_Mst.emailId = this.employeeForm.value.EmailId;
        employee_Mst.designation = this.employeeForm.value.Designation;
        employee_Mst.hobbies = this.hobbiesarr.join(',');
        employee_Mst.salary = this.employeeForm.value.Salary.toString();
        employee_Mst.country = this.employeeForm.value.Country;
        employee_Mst.city = this.employeeForm.value.City;
        employee_Mst.image = this.profileImage;
        employee_Mst.password = this.employeeForm.value.Password;
        this._employeeService.addemployee(employee_Mst).subscribe((Response) => {
          this.getAllEmployee();
        });
        this.visible = false;
      }
    } else {
      this.Hobbies.forEach((res) => {
        if (res.selected == true) {
          this.hobbiesarr.push(res.value);
        }
      });
      const employee_Mst = new Employee_Mst();
      employee_Mst.id = this.employeeForm.value.Id;
      employee_Mst.name = this.employeeForm.value.Name;
      employee_Mst.dob = this.employeeForm.value.DOB;
      employee_Mst.gender = this.employeeForm.value.Gender;
      employee_Mst.phoneNo = this.employeeForm.value.PhoneNo;
      employee_Mst.address = this.employeeForm.value.Address;
      employee_Mst.emailId = this.employeeForm.value.EmailId;
      employee_Mst.designation = this.employeeForm.value.Designation;
      employee_Mst.hobbies = this.hobbiesarr.join(',');
      employee_Mst.salary = this.employeeForm.value.Salary;
      employee_Mst.country = this.employeeForm.value.Country;
      employee_Mst.city = this.employeeForm.value.City;
      employee_Mst.image = this.profileImage;
      this._employeeService
        .Updateemployee(employee_Mst)
        .subscribe((Response) => {
          this.getAllEmployee();
        });
      this.visible = false;
    }
  }

  onSelectEvent(event: any) {
    var file = event.files.length;
    for (let i = 0; i < file; i++) {
      var reader = new FileReader();
      reader.onload = (event: any) => {
        this.profileImage = event.target.result;
      };
      reader.readAsDataURL(event.files[i]);
    }
  }

  oncheckboxchange(Hobbies: any) {
    this.hobbiesarray = this.employeeForm.get('Hobbie') as FormArray;
    if (Hobbies.value) {
      this.Hobbies.forEach((res) => {
        if (Hobbies.value == res.value) {
          res.selected = true;
        }
      });
      this.hobbiesarray.push(new FormControl(Hobbies.value));
    }   
  }

  changecity(event: any) {
    this._employeeService.getCity(event.value).subscribe((city) => {
      this.city = city;
    });
  }

  openDialog() {
    this.visible = true;
    this.employeeTitle = 'Add Employee';
  }

  Edit(id: number) {
    this.employeeTitle = 'Edit Employee';
    this._employeeService.editemployee(id).subscribe((data) => {
      this.profileImage = data.image;
      this.getcitybyId(data.city);
      var hobbies = data.hobbies.split(',');
      this.Hobbies.forEach((allHobbies) => {
        allHobbies.selected = false;
        hobbies.forEach((savedHobbies) => {
          if (allHobbies.value.toLowerCase() == savedHobbies.toLowerCase()) {
            allHobbies.selected = true;
          }
        });
      });
      let dt = new Date(data.dob);
      this.employeeForm.patchValue({
        Id: id,
        Name: data.name,
        DOB: dt,
        Gender: data.gender,
        PhoneNo: data.phoneNo,
        Address: data.address,
        EmailId: data.emailId,
        Designation: data.designation,
        Salary: data.salary,
        Country: data.country,
        City: data.city,
      });
      this.visible = true;
    });
  }

  getcitybyId(id: any) {
    this._employeeService.getcityById(id).subscribe((city) => {
      this.city = city;
    });
  }

  delete(id: number) {
    this._confirmationService.confirm({
      message: 'Are you sure you want to Delete this Record ?',
      header: 'Confirm',
      icon: 'pi pi-exclamation-triangle',
      accept: () => {
        this._employeeService.deleteemployee(id).subscribe((data) => {
          this.getAllEmployee();
        });
      },
    });
  }

  removeImage() {
    this.profileImage = '';
  }
}

Step6: Add the CSS in your registration.component.css

.set-min-width ::ng-deep .p-dialog {
    min-height: 100%;
}

Step7: Write below code in registration.component.html

<div class="grid">
            <div class="col-12 text-right">
                <button pButton type="button" class="p-button-raised p-button-rounded"
                    (click)="openDialog()">Registration</button>
            </div>
</div>
<div class="grid">
    <div class="col-12">
        <p-table [value]="Employee_Mst">
            <ng-template pTemplate="header">
                <tr>
                    <th>Name</th>
                    <th>DOB</th>
                    <th>Gender</th>
                    <th>PhoneNo</th>
                    <th>Address</th>
                    <th>EmailId</th>
                    <th>Designation</th>
                    <th>Hobbies</th>
                    <th>Salary</th>
                    <th>Country</th>
                    <th>City</th>
                    <th>Image</th>
                    <th class="text-center">Edit</th>
                    <th class="text-center">Delete</th>
                </tr>
            </ng-template>
            <ng-template pTemplate="body" let-Employee_Mst>
                <tr>
                    <td>{{Employee_Mst.name | titlecase}}</td>
                    <td>{{Employee_Mst.dob | date :'shortDate'}}</td>
                    <td>{{Employee_Mst.gender }}</td>
                    <td>{{Employee_Mst.phoneNo}}</td>
                    <td>{{Employee_Mst.address | titlecase}}</td>
                    <td>{{Employee_Mst.emailId}}</td>
                    <td>{{Employee_Mst.designation}}</td>
                    <td>{{Employee_Mst.hobbies}}</td>
                    <td>{{Employee_Mst.salary}}</td>
                    <td>{{Employee_Mst.country}}</td>
                    <td>{{Employee_Mst.city}}</td>
                    <td>
                        <img style="object-fit: cover;" height="40px" width="40px"
                            [src]="Employee_Mst.image ? Employee_Mst.image : 'assets/Images/profile4.png'">
                    </td>
                    <td class="text-center"> 
                        <button type="button" pButton icon="pi pi-user-edit" iconPos="left" (click)="Edit(Employee_Mst.id)" label="Edit"></button>
                    </td>
                    <td class="text-center">
                        <button type="button" class="p-button-secondary" pButton icon="pi pi-times" iconPos="left" (click)="delete(Employee_Mst.id)" label="Delete"></button>
                    </td>
                </tr>
            </ng-template>
        </p-table>
    </div>
</div>
<p-dialog [(visible)]="visible" [header]="employeeTitle" [style]="{width:'760px'}" class="set-min-width">
    <div class="grid">
        <div class="col-12">
            <form [formGroup]="employeeForm" (ngSubmit)="onSubmit()">
                <div class="grid">
                    <div class="col-2 mt-4">
                        <label>Name:</label>
                    </div>
                    <div class="col-10">
                        <input type="text" name="Name" pInputText id="Name" required autofocus class="inputfield w-full mt-4"
                            formControlName="Name">
                        <span *ngIf="!employeeForm.get('Name')?.value && submitted"
                            style="margin-top: 2px;color: red;">*</span>
                    </div>
                </div>
                <div class="grid">
                    <div class="col-2">
                        <label>DOB:</label>
                    </div>
                    <div class="col-10">
                        <p-calendar id="DOB" class="w-full set-padding" formControlName="DOB" name="DOB" appendTo="body"
                            [inputStyle]="{'padding-right': '402px'}">
                        </p-calendar>
                        <span *ngIf="!employeeForm.get('DOB')?.value && submitted"
                            style="margin-top: 2px;color: red;">*</span>
                    </div>
                </div>
                <div class="grid">
                    <div class="col-2">
                        <label>Gender:</label>
                    </div>
                    <div class="col-10">
                        <p-radioButton name="Gender" value="Male" formControlName="Gender" class="mr-1"></p-radioButton>Male
                        <p-radioButton name="Gender" value="Female" formControlName="Gender" class="mr-1"></p-radioButton>Female
                        <span *ngIf="!employeeForm.get('Gender')?.value && submitted"
                            style="margin-top: 2px;color: red;">*</span>
                    </div>
                </div>
                <div class="grid">
                    <div class="col-2">
                        <label>PhoneNo:</label>
                    </div>
                    <div class="col-10">
                        <p-inputNumber formControlName="PhoneNo" [inputStyle]="{'padding-right': '383px'}">
                        </p-inputNumber>
                        <span *ngIf="!employeeForm.get('PhoneNo')?.value && submitted"
                            style="margin-top: 2px;color: red;">*</span>
                    </div>
                </div>
                <div class="grid">
                    <div class="col-2">
                        <label>Address:</label>
                    </div>
                    <div class="col-10">
                        <textarea [rows]="5" [cols]="75" pInputTextarea autoResize="autoResize"
                            formControlName="Address"></textarea>
                        <span *ngIf="!employeeForm.get('Address')?.value && submitted"
                            style="margin-top: 2px;color: red;">*</span>
                    </div>
                </div>
                <div class="grid">
                    <div class="col-2">
                        <label>EmailId: </label>
                    </div>
                    <div class="col-10">
                        <input type="text" pInputText formControlName="EmailId" style='padding-right: 383px;' />
                        <span *ngIf="!employeeForm.get('EmailId')?.value && submitted"
                            style="margin-top: 2px;color: red;">*</span>
                    </div>
                </div>
                <div class="grid">
                    <div class="col-2">
                        <label>Designation: </label>
                    </div>
                    <div class="col-10">
                        <input type="text" pInputText formControlName="Designation" style='padding-right: 383px;' />
                        <span *ngIf="!employeeForm.get('Designation')?.value && submitted"
                            style="margin-top: 2px;color: red;">*</span>
                    </div>
                </div>
                <div class="grid">
                    <div class="col-2">
                        <label>Hobbies: </label>
                    </div>
                    <div class="col-10">
                        <div *ngFor="let Hobbies of Hobbies; let i=index" class="mb-1">
                            <p-checkbox value="Hobbies.value" [binary]="hobbieCheckbox"
                                (onChange)="oncheckboxchange(Hobbies)" [checked]="Hobbies.selected"></p-checkbox>
                            {{Hobbies.name}}
                        </div>
                        <span *ngIf="!employeeForm.get('Hobbie')?.value && submitted"
                            style="margin-top: 2px;color: red;">*</span>
                    </div>
                </div>
                <div class="grid">
                    <div class="col-2">
                        <label>Salary: </label>
                    </div>
                    <div class="col-10">
                        <p-inputNumber formControlName="Salary" [inputStyle]="{'padding-right': '383px'}">
                        </p-inputNumber>
                        <span *ngIf="!employeeForm.get('Salary')?.value && submitted"
                            style="margin-top: 2px;color: red;">*</span>
                    </div>
                </div>
                <div class="grid">
                    <div class="col-2">
                        <label>Country: </label>
                    </div>
                    <div class="col-10">
                        <p-dropdown [options]="country" optionLabel="countryName" optionValue="countryId" name="country"
                            appendTo="body" placeholder="--Choose Country--" autoWidth="false"
                            [style]="{'width':'100%'}" formControlName="Country" (onChange)="changecity($event)">
                        </p-dropdown>
                        <span *ngIf="!employeeForm.get('Country')?.value && submitted"
                            style="margin-top: 2px;color: red;">*</span>
                    </div>
                </div>
                <div class="grid">
                    <div class="col-2">
                        <label>City: </label>
                    </div>
                    <div class="col-10">
                        <p-dropdown [options]="city" optionLabel="cityName" optionValue="cityId" name="city"
                            appendTo="body" placeholder="--Choose City--" autoWidth="false" [style]="{'width':'100%'}"
                            formControlName="City"></p-dropdown>
                        <span *ngIf="!employeeForm.get('City')?.value && submitted"
                            style="margin-top: 2px;color: red;">*</span>
                    </div>
                </div>
                <div class="grid" *ngIf="!employeeForm.get('Id')?.value">
                    <div class="col-2">
                        <label>PassWord: </label>
                    </div>
                    <div class="col-4">
                        <input type="password" pPassword id="Password" formControlName="Password" style="padding-right: 85px;"
                            />
                        <span *ngIf="!employeeForm.get('Password')?.value && submitted"
                            style="margin-top: 2px;color: red;">*</span>
                    </div>
                    <div class="col-4">
                        <input type="password" pPassword id="ConfirmPassword" formControlName="ConfirmPassword" placeholder="Confirm Password" style="margin-left: 50px;
                        padding-right: 97px;"
                        />
                    <span *ngIf="checkConfirmPassword" style="color: red;">{{checkConfirmPassword}}</span>
                    </div>
                </div>
                <div class="grid">
                    <div class="col-2">
                        <label>FileUpload: </label>
                    </div>
                    <div class="col-10">
                        <p-fileUpload name="document[]" (onSelect)="onSelectEvent($event)" [showUploadButton]="false"
                            [showCancelButton]="false" cancelIcon="pi pi-times">
                            <ng-template pTemplate="content">
                                <div *ngIf="profileImage && employeeForm.get('Id')?.value">
                                    <div class="grid">
                                        <div class="col-8"><img style="object-fit: cover;" height="40px" width="40px"
                                                src="{{profileImage}}"></div>
                                        <div class="col-4">
                                            <p-button label="Cancle" icon="pi pi-times" iconPos="left"
                                                (click)="removeImage()"></p-button>
                                        </div>
                                    </div>
                                </div>
                            </ng-template>
                        </p-fileUpload>
                        <span *ngIf="submitted" style="margin-top: 2px;color: red;">*</span>
                    </div>
                </div>
                <div class="grid">
                    <div class="col-2">
                    </div>
                    <div class="col-10 text-right">
                        <button pButton type="submit" label="Save" *ngIf="!employeeForm.get('Id')?.value"></button>
                        <button pButton type="submit" *ngIf="employeeForm.get('Id')?.value">Update</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</p-dialog>
<p-confirmDialog [style]="{width: '450px'}"></p-confirmDialog>

Step8: npm start and see output

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories