Angular Template Driven Forms

By | | Updated : 2021-04-11 | Viewed : 44 times

Angular Template Driven Forms

Angular provides different types of forms for UI input feeds. One of the options for forms in Angular is Angular Template Driven Forms. The current article explains Template Driven Forms. We will look into these Template-driven forms for example.

Angular Template Driven Forms

Angular Template Driven Forms have depended on directive ngModel. When we feed the input to the forms then that data is handled by ngModel by managing the formControl instance.

Angular Template Driven Forms Example

We will look at template Html and control component class to understand how to create the Angular Template Driven Forms.

app.component.html
<div class="container">
  <div class="row">
    <div class="col-md-8 offset-md-2">
      <form (ngSubmit)="onSubmit()" name="form" novalidate>
        <div class="form-group">
          <label for="firstName">First Name</label>
          <input #firstName="ngModel" [(ngModel)]="model.firstName" class="form-control" name="firstName" required
                 type="text"/>

        </div>
        <div class="form-group">
          <label for="lastName">Last Name</label>
          <input #lastName="ngModel" [(ngModel)]="model.lastName" class="form-control" name="lastName" required
                 type="text"/>

        </div>
        <div class="form-group">
          <label for="email">Email</label>
          <input #email="ngModel" [(ngModel)]="model.email" class="form-control" email name="email" required
                 type="text"/>

        </div>
        <div class="form-group">
          <label for="password">Password</label>
          <input #password="ngModel" [(ngModel)]="model.password" class="form-control" minlength="6" name="password"
                 required type="password"/>

        </div>
        <div class="form-group">
          <button class="btn btn-primary">Register</button>
        </div>
      </form>
    </div>
  </div>
</div>
app.component.ts
import {Component} from \'@angular/core\';

@Component({
  selector: \'app-root\',
  templateUrl: \'./app.component.html\',
  styleUrls: [\'./app.component.css\']
})
export class AppComponent {
  title = \'Angular-Template-Driven-Forms-Example-App1\';
  model: any = {};

  onSubmit() {
    alert(\'SUCCESS!! :-)\n\n\' + JSON.stringify(this.model))
  }

}

We will observe the first template Html app.component.html. Here we have added the form fields and coded them with [(ngModel)]="model.firstName" to bind the field data.

In the same way, we have added ngModel directive to the remaining fields in the template Html app.component.html. Please notice the same.

Notice component control class we accessed the data using model and displayed entire data in the alert notification.

To get the full-fledged example you can refer to the repository Angular-Template-Driven-Forms-Example-App

Leave A Reply