Angular – Template-drive Forms

By | 30/10/2019

Angular – Reactive Forms

In this post, we will see how to define a Form, using Template-drive forms approach, for creating new users in our usual angular project.
First of all, we create another component called newusertd and then, we will add it in app-routing and topmenu:

ng g c newusertd


import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ListusersComponent } from './listusers/listusers.component';
import { HomepageComponent} from './homepage/homepage.component';
import { NewuserComponent} from './newuser/newuser.component';
import { NewusertdComponent } from './newusertd/newusertd.component';

const routes: Routes = [
  { path: '', pathMatch: 'full', redirectTo: 'homepage'},
  { path: 'homepage', component: HomepageComponent },
  { path: 'listusers', component: ListusersComponent },
  { path: 'newuser', component: NewuserComponent },
  { path: 'newuser2', component: NewusertdComponent },
  { path: '**', pathMatch: 'full', redirectTo: 'homepage' }  
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
export class AppRoutingModule { }


<nav class="navbar navbar-dark bg-dark mb-5">
  <a class="navbar-brand" routerLink="homepage">[Manage Users]</a>
  <div class="navbar-expand mr-auto">
    <ul class="nav navbar-nav" routerLinkActive="active">
        <li class="nav-item"><a class="nav-link" routerLink="/listusers">List Users</a></li>
        <li class="nav-item"><a class="nav-link" routerLink="/newuser">Create User</a></li>
        <li class="nav-item"><a class="nav-link" routerLink="/newuser2">Create User Template</a></li>

Now, in order to use the Form with Template Drive, we have to add  the component FormsModule in app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http'; 
import { FormsModule }   from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ListusersComponent } from './listusers/listusers.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { TopmenuComponent } from './topmenu/topmenu.component';
import { HomepageComponent } from './homepage/homepage.component';
import { NewuserComponent } from './newuser/newuser.component';
import { NewusertdComponent } from './newusertd/newusertd.component';

  declarations: [
  imports: [
  providers: [],
  bootstrap: [AppComponent]
export class AppModule { }

Finally, we have to modify three files:


import { Component, OnInit } from '@angular/core';
import { User } from '../user';
import { WebapiuserService } from '../webapiuser.service';
import { Router } from '@angular/router';

  selector: 'app-newusertd',
  templateUrl: './newusertd.component.html',
  styleUrls: ['./newusertd.component.css']
export class NewusertdComponent implements OnInit {
  // Like the React Form, I put in the code the list of
  // typeUser.
  // In a real application it could be better using a 
  // Web service in order to get the list 
  typeUser: Array<string> = [

  // Definition of the object that will use into the Form
  objUser: User = new User();

  constructor(private serviceuser: WebapiuserService, private router: Router) { }

  ngOnInit() {

    // call the method to create a new user
      // if it's ok, call the method newUserOk
      data => this.newUserOK(),
      error => console.log("Error", error)

    // The system will show a message
    alert("New user " + this.objUser.username + "was created!");
    // and will go to the List Users page


<div class="jumbotron">
    <div class="container">
        <div class="row">
            <div class="col-md-6 offset-md-3">
                <h3>New User with Template Driven</h3>
                <form (ngSubmit)="onSubmit()" #userForm="ngForm">
                    <div class="form-group">
                        <label for="username">Username</label>
                        <input type="text" class="form-control" id="username" required [(ngModel)]="objUser.username" name="username" #username="ngModel">
                        <div [hidden]="username.valid || username.pristine"  class="alert alert-danger">
                            Username is required
                    <div class="form-group">
                        <label>Type User Name</label>
                        <select class="form-control" name="typeUserName" id="typeUserName" required [(ngModel)]="objUser.typeUserName" #typeUserName="ngModel">
                            <option *ngFor="let item of typeUser" [ngValue]="item">{{item}}</option>
                        <div [hidden]="typeUserName.valid || typeUserName.pristine"  class="alert alert-danger">
                            typeUserName is required
                    <button type="submit" class="btn btn-success" [disabled]="!userForm.form.valid">Register</button>


.ng-valid[required], .ng-valid.required  
    border-left: 5px solid #42A948; /* green */
  border-left: 5px solid #a94442; /* red */

Now, in order to verify that the Form works fine, we run (with the command ng serve) the application and we try to add a new user:

Leave a Reply

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