Show List

Angular Forms

Angular provides two ways to build forms: template-driven forms and reactive forms. Both approaches allow you to create, validate, and submit forms in your Angular application, but they have different advantages and use cases.

  1. Template-driven Forms:

Template-driven forms use Angular directives and data binding to create forms in the template, without writing any JavaScript code. You can use ngModel and form-specific directives like ngForm, ngSubmit, and ngModelGroup to build forms in the template.

Here is an example of a simple template-driven form in Angular:

<form #f="ngForm" (ngSubmit)="onSubmit(f)">

  <div>
    <label for="email">Email:</label>
    <input type="email" id="email" name="email" ngModel required>
  </div>
  <div>
    <label for="password">Password:</label>
    <input type="password" id="password" name="password" ngModel required>
  </div>
  <button type="submit">Submit</button>
</form>

In this example, we are using the ngForm directive to create a reference to the form in the template. The ngModel directive is used to bind the form fields to the component's properties. The required attribute is used to add a required validation to the form fields. Finally, the ngSubmit directive is used to handle the form submission.

  1. Reactive Forms:

Reactive forms, also known as model-driven forms, use a programmatic approach to building forms in Angular. You create a form in the component class using the FormControl, FormGroup, and FormArray classes, and then bind the form to the template using data binding.

Here is an example of a simple reactive form in Angular:

import { FormControl, FormGroup } from '@angular/forms';

...

loginForm = new FormGroup({
  email: new FormControl(''),
  password: new FormControl(''),
});

onSubmit() {
  console.log(this.loginForm.value);
}
<form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
  <div>
    <label for="email">Email:</label>
    <input type="email" id="email" formControlName="email">
  </div>
  <div>
    <label for="password">Password:</label>
    <input type="password" id="password" formControlName="password">
  </div>
  <button type="submit">Submit</button>
</form>

In this example, we are using the FormGroup and FormControl classes to create a form group and form controls, and then bind them to the template using the formGroup directive and the formControlName attribute. The form submission is handled in the same way as in the template-driven form example.

Both template-driven and reactive forms have their own benefits and use cases, and the choice of which one to use depends on your specific requirements. Template-driven forms are simple to use and are suitable for small, simple forms, while reactive forms offer more control and are better suited for complex forms with many fields and validation rules.


    Leave a Comment


  • captcha text