angular reactive form

How to implement Reactive Form with Prime NG

Reactive forms

Reactive forms provide a model-driven approach to handling form inputs whose values change over time. This guide shows you how to create and update a basic form control, progress to using multiple controls in a group, validate form values, and create dynamic forms where you can add or remove controls at run time.

Reactive forms differ from template-driven forms in distinct ways. Reactive forms provide more predictability with synchronous access to the data model, immutability with observable operators, and change tracking through observable streams.

Template-driven forms allow direct access to modify data in your template, but are less explicit than reactive forms because they rely on directives embedded in the template, along with mutable data to track changes asynchronously. See the Forms Overview for detailed comparisons between the two paradigms.


— As per https://angular.io/guide/reactive-forms

Here we are using prime NG version :

"primeicons": "^3.0.0-rc.1",
"primeng": "8.0.4", 

Important Module which need to create Angular Reactive Form and Prime NG Table.

import { ReactiveFormsModule } from "@angular/forms";
import { DialogService, MessageService } from "primeng/api";
import { CalendarModule } from "primeng/calendar";
import { TableModule } from "primeng/table";
import { ToastModule } from "primeng/toast";

HTML CODE:

<div class="card m-3">
  <h5 class="card-header">Dynamic Reactive form with Prime NG P-table</h5>
  <div class="card-body">
    <form [formGroup]="userForm">
      <div formArrayName="usersDetails">
        <p-table [value]="usersDetails.controls" [(selection)]="selectedUsers">
          <ng-template pTemplate="header">
            <tr>
              <th style="width: 5%">
              </th>
              <th style="width: 20%">Name</th>
              <th style="width: 30%">Email</th>
              <th style="width: 20%">Gender</th>
              <th>Date Of Birth</th>
            </tr>
          </ng-template>
          <ng-template pTemplate="body" let-controls let-i="rowIndex">
            <tr [formGroupName]="i">
              <td>
                <p-tableCheckbox [value]="i+1"></p-tableCheckbox>
              </td>
              <td><input type="text" formControlName="name" class="form-control" /></td>
              <td> <input type="email" formControlName="email" class="form-control" />
                <span style="color:red" *ngIf="userDetailsControls(i)?.email.errors?.required">Email is Required</span>
                <span style="color:red" *ngIf="userDetailsControls(i)?.email.errors?.email">Please provide a valid
                  email</span>
              </td>
              <td>
                <p-dropdown [options]="genderOptions" formControlName="gender"></p-dropdown>
              </td>
              <td>
                <p-calendar appendTo="body" formControlName="dob" dateFormat="dd/mm/yy" showIcon="true"
                  showButtonBar="true" [maxDate]="maxDateValue"></p-calendar>
              </td>
            </tr>

          </ng-template>
        </p-table>
      </div>
    </form>
    <div style="margin-top: 10px;">
      <button class="btn btn-primary mr-1" (click)="onAdd()">Add New Row</button>
      <button [disabled]="usersDetails.controls.length === 1" class="btn btn-primary mr-1" (click)="onDelete()">Delete
        Selected Row</button>
      <button [disabled]="userForm.invalid" class="btn btn-primary mr-1" (click)="onSubmit()">Submit</button>
    </div>
  </div>
</div>
<p-toast [style]="{marginTop: '80px'}"></p-toast>
<div>
  {{data}}
</div>

How to implement Reactive Form with Prime NG


Core things of above code:

We have created an angular reactive form with <form [formGroup]="userForm">.
We will add dynamic fields into a form array named  <div formArrayName = "usersDetails">.
Created p table inside form with values formarray controls and pass selection property to save selections
 <p-table [value]="usersDetails.controls" [(selection)]="selectedUsers">.
Now we have to define formgroup Name for each added row with  <tr [formGroupName]="i">
Added Checkbox like <p-tableCheckbox [value]="i+1"></p-tableCheckbox> - Here we have added
value like "i+1" because 0 is falsy value.
To create date field with prime ng table:

  <p-calendar appendTo="body" formControlName="dob" dateFormat="dd/mm/yy" showIcon="true"
                  showButtonBar="true" [maxDate]="maxDateValue"></p-calendar>


Component.ts File

import { Component, OnInit } from "@angular/core";
import {
  FormArray,
  FormBuilder,
  FormControl,
  FormGroup,
  Validators,
} from "@angular/forms";
import { MessageService, SelectItem } from "primeng/api";

@Component({
  selector: "app-user-form",
  templateUrl: "./user-form.component.html",
  styleUrls: ["./user-form.component.scss"],
})
export class UserFormComponent implements OnInit {
  protected data;
  // Defined protected because it is using in HTML page
  protected maxDateValue = new Date();

  /**
   * Defining static gender option for dropdown
   */
  genderOptions: SelectItem[] = [
    { label: "Select Gender", value: null },
    { label: "Male", value: "male" },
    { label: "Female", value: "female" },
  ];
  selectedUsers: any = [];
  userForm: FormGroup;
  /**
   * Defined some values for Form - these values will be pre populated
   */
  values = [
    { name: "John", email: "John@gmail.com", gender: "male", dob: "20/1/1991" },
    {
      name: "David ",
      email: "david.restro@gmail.com",
      gender: "male",
      dob: "20/1/1965",
    },
  ];

  /**
   * Return user details form array
   */
  get usersDetails(): FormArray {
    return this.userForm.get("usersDetails") as FormArray;
  }

  /**
   *
   * @param formBuilder - Required Form builder to create angular reactive form
   * @param messageService - Message service is required to display messages (This is Prime NG message service)
   */
  constructor(
    private formBuilder: FormBuilder,
    private messageService: MessageService
  ) {}

  ngOnInit() {
    this.userForm = this.formBuilder.group({
      usersDetails: this.formBuilder.array([]),
    });
    this.populateData();
  }

  /**
   * Click on add button to add new row in prime ng table
   */
  onAdd() {
    this.userForm.markAllAsTouched();
    this.usersDetails.push(this.addControls());
  }

  /**
   * delete an existing row
   */
  onDelete() {
    if (this.selectedUsers.length < 1) {
      this.messageService.add({
        severity: "warn",
        summary: "Info",
        detail: "Please select a record to delete!",
      });
      return;
    }
    console.log(this.selectedUsers);
    for (var i = this.selectedUsers.length - 1; i >= 0; i--) {
      this.usersDetails.controls.splice(this.selectedUsers[i] - 1, 1);
    }
    this.messageService.add({
      severity: "success",
      summary: "Success",
      detail: "Selected records deleted!",
    });

    this.selectedUsers = [];
  }

  /**
   * click on  submit button
   */
  onSubmit() {
    this.data = JSON.stringify(this.usersDetails.value);
  }

  /**
   * return user detail controls for given index
   * @param index - number
   */
  userDetailsControls(index: number) {
    return this.usersDetails.controls[index]["controls"];
  }

  /**
   * Add control into Form
   */
  private addControls() {
    return new FormGroup({
      name: new FormControl(""),
      email: new FormControl("", [Validators.email, Validators.required]),
      gender: new FormControl(null),
      dob: new FormControl(""),
    });
  }

  /**
   * Populate data into Form
   */
  private populateData() {
    this.values.forEach((data, index) => {
      this.onAdd();
      this.usersDetails.controls[index].setValue(data);
    });
  }
}

How to implement Reactive Form with Prime NG

Angular reactive form: https://angular.io/guide/reactive-forms

Learn Konva JS: https://www.jsmount.com/konva-js-event-handling/

How to implement Reactive Form with Prime NG

  1. Hello, after reading this amazing post i am as well delighted to share my knowledge here with mates. Appolonia Dickie Mannos

  2. Well I sincerely enjoyed studying it. This article provided by you is very constructive for good planning. Genovera Vic Alexia

Comments are closed.