Angular, Forms

Angular Submit a form programmatically

Spread the love

Need of Angular Submit a form programmatically for different type of design and logic. Like your submit button present out of form block or you have call submit method from ts file. Angular Submit a form programmatically for that mechanism we use here ViewChild template reference with NgForm intance. Follow the bold key points for the main points of this tutorial.

Here we define two way of form submit in this article below

  1. Form submit dynamically or programmatically in angular
  2. Form submit button located outside of a form in html

1. Form Submit dynamically or programmatically in Angular

Form Submit dynamically or programmatically  in Angular
submit the form outside the form block with your different business logic

app.component.html

<div class="contacts-list">
  <table>
    <th>Id</th>
    <th>Name</th>
    <th>Department</th>
    <th>Email</th>
    <th>Edit</th>
    <tr
      *ngFor="let contact of contactsList;trackBy: trackByFn;
let i = index
"
    >
      <td>{{ contact.id }}</td>
      <td>{{ contact.name }}</td>
      <td>{{ contact.department }}</td>
      <td>{{ contact.email }}</td>
      <td class="edit">
        <a href="javascript:void(0)" (click)="editForm(i)">
          Edit
        </a>
      </td>
    </tr>
  </table>
</div>
<ng-template [ngIf]="isAddFormOpen">
<form
    [formGroup]="contactsForm"
    #addform="ngForm"
    (ngSubmit)="submitContactsForm()"
  >
    <label for="name" class="form-group-label">Name</label>
    <input
      formControlName="name"
      type="text"
      name="name"
      id="name"
      class="form-input"
      placeholder="Enter Name"
    />
    <br />
    <label for="department" class="form-group-label">Department</label>
    <input
      formControlName="department"
      type="text"
      name="department"
      id="department"
      class="form-input"
      placeholder="Enter Department"
    />
    <br />
    <label for="eMail" class="form-group-label">Email</label>
    <input
      formControlName="email"
      type="email"
      name="email"
      id="email"
      class="form-input"
      placeholder="Enter email"
    />
  </form>
</ng-template>
<div class="form-button-with-icon" *ngIf="!isEdit">
  <a href="javascript:void(0)">
    <span>
      <i class="icon-plus"></i>
    </span>
    <p (click)="submitForm()">Add Contact</p>
  </a>
</div>
<div class="form-button-with-icon" *ngIf="isEdit">
  <a href="javascript:void(0)">
    <span>
      <i class="icon-plus"></i>
    </span>
    <p (click)="submitForm()">Update Contact</p>
  </a>
</div>

app.component.ts

import { Component, ViewChild } from '@angular/core';
import {
  FormBuilder,
  FormGroup,
  Validators,
  NgForm
} from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  @ViewChild('addform') addform: NgForm;
  contactsForm: FormGroup;
  public isAddFormOpen = false;
  public isEdit = false;
  public contactsList = [];
  constructor(private _fb: FormBuilder) {
    this.contactsForm = this._fb.group({
      id: [Number],
      name: [
        '',
        [
          Validators.required,
          Validators.pattern('^[a-zA-Z-,]+(s{0,1}[a-zA-Z-, ])*$')
        ]
      ],
      department: ['', [Validators.required]],
      email: [
        '',
        [
          Validators.required
          //Validators.pattern('[A-Za-z0-9._%-]+@[A-Za-z0-9._%-]+\\.[a-z]{2,3}')
        ]
      ]
    });
  }

  get formControls() {
    return this.contactsForm.controls;
  }

  trackByFn(index, entity) {
    return entity.email;
  }

  submitForm() {
    if (this.isAddFormOpen) {
      this.addform.onSubmit(undefined);
    } else {
      this.isAddFormOpen = true;
    }
  }

  editForm(i) {
    this.isEdit = true;
    this.contactsForm.patchValue(this.contactsList[i]);
    this.isAddFormOpen = true;
  }

  submitContactsForm() {
    if (this.contactsForm.invalid) {
      return;
    } else if (this.isEdit) {
      let index = this.contactsList.findIndex(
        x => x.id == this.contactsForm.value.id
      );
      this.contactsList[index] = { ...this.contactsForm.value };

      console.log(this.contactsList);
      this.isEdit = false;
      this.isAddFormOpen = false;
      this.addform.reset();
    } else {
      this.contactsForm.get('id').setValue(this.contactsList.length + 1);
      this.contactsList.push(this.contactsForm.value);
      this.isAddFormOpen = false;
      this.addform.reset();
    }
  }
}

2. Form submit button located outside of a form in html

Specifies the form object the object belongs to. The value of this feature must be an id identifier id of the object in the same text.

Referances

Thank you! Any confusion comment in comment section and please don’t forget to Like our Facebook page to get new interested articles.


Spread the love

About Chandra

Technology lover. Professionally Software Developer and write some Technical Blog to help newcomer.
View all posts by Chandra →

2 thoughts on “Angular Submit a form programmatically

Leave a Reply

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