Implement Angular Reactive Forms

Hi Friends, This is Lakshman here.

As part of the Series "Angular Best Practices".

Today, We will Implement Angular Reactive Forms.

Pre-requisites:

The pre-requisites are

For Code Editor its VS Code with Remote Container.

If you want to develop inside Container - Check This Out

Reactive Forms

In Every Angular Application, there will be at least Form to Fill by End User.

There are always two ways to implement Forms,

  • Form.
  • Reactive Forms.

Its Benefits are

  • Ability to create Dynamic Forms.
  • Helps to set Validator initially while creating form via Form Group.
  • Easy Validation Options.

Implementation:

Step 1: Add Dependencies

Add ReactiveFormsModule in app.module.ts & respective Module File.


import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  ...
  imports: [
    ...
    ReactiveFormsModule,
    ...
  ]
})

Step 2: Add Reactive Form Builder and Form

Add the Below Code on Controller File for Sample Todo List with Reactive Form


//#region Entry Variables

view: string;
entryForm: FormGroup;
todoId: string;

//#endregion

constructor(private route: ActivatedRoute, private formBuilder: FormBuilder, private service: TodoListService) {
    this.createForm();
}

 //#region Add Todo Variables

  createForm() {
    this.view = "Add";
    this.entryForm = this.formBuilder.group({
      Task: ['', Validators.required],
      IsCompleted: [false],
    });
  }

  resetForm() {
    this.todoId = "";
    this.view = "Add";
    this.entryForm.reset();
  }

  updateForm(todo: Todo) {
    this.todoId = todo.Id;
    this.view = "Update";
    this.entryForm.setValue({
      Task: todo.Task,
      IsCompleted: todo.IsCompleted
    });
  }

  Submit() {
    const todo$ =
      this.todoId !== ''
        ? this.service.updateTodo(this.todoId, this.entryForm.value)
        : this.service.addTodo(this.entryForm.value);
    todo$
      .subscribe(
        (todos) => {
          this.TodoList = todos;
          alert(`${this.view} Successfully`);
          this.resetForm();
        },
        (error) => {
          console.debug(`Todo Entry error: ${error}`);
        }
      );
  }

  //#endregion

Use the below code On HTML as below,

...
<tr *ngFor="let item of TodoList">
  <td>{{ item.Task }}</td>
  <td>{{ item.IsCompleted ? "Completed" : "Yet To Complete" }}</td>
  <td><i class="fas fa-edit" (click)="updateForm(item)"></i></td>
</tr>
<tr *ngIf="TodoList.length == 0">
  <td colspan="2">No Todo List Available</td>
</tr>
...
<form [formGroup]="entryForm" (ngSubmit)="Submit()">
  <!-- Text input -->
  <div class="form-group mb-4">
    <label class="form-label" for="textAreaTask">Task</label>
    <textarea
      class="form-control"
      formControlName="Task"
      id="textAreaTask"
      rows="2"
    ></textarea>
  </div>

  <div class="form-check form-group mb-3">
    <input
      class="form-check-input"
      type="checkbox"
      id="frmIsCompleted"
      formControlName="IsCompleted"
      style="margin-left: -1.5em;"
    />
    <label class="form-check-label" for="frmIsCompleted"> IsCompleted </label>
  </div>

  <!-- Submit button -->
  <button type="reset" class="btn btn-warning mb-4" (click)="resetForm()">
    Cancel
  </button>
  <button
    type="submit"
    class="ms-4 btn btn-primary mb-4"
    [disabled]="entryForm.invalid"
  >
    {{view}} Todo
  </button>
</form>

HTML, Controller & Service Code is available on Github via Here

Once all the steps completed.

We can start using this reactive form in the module.

That wrap up the Implement Angular Reactive Forms

You may also access to source on GitHub by Click Here

On-road head, we will discuss a lot of things.

Looking forward to your comments and share your feedback.

Until that, I am Lakshman, Signing Off.

Comments

Popular posts from this blog

Model Mapper in Angular

Implement Logging in Angular with Firebase

Dockerize Angular App for Dev