Today we’re going to look at template-driven approach to forms with the wonders of ngModel. Tomorrow we’ll look at the reactive approach to forms using backing code for validation config.

You can always grab tagged source code on the GitHub repo which will be tagged day1, day2, etc.

You can Subscribe to my Fresh Bytecode channel for regular Java/Web-related screencasts, or if you’re just into Angular, checkout the YouTube Playlist where I update all the episodes in this series as they come out.

Here’s the script so you can follow along at home:

[ ] First, let’s generate a login form

ng g c login

[ ] And add it to our module in app.module.ts

import { LoginComponent } from './login';

declarations: [ AppComponent, FeedComponent, MenuComponent, FriendsComponent, FriendComponent, MessagesComponent, LoginComponent ],

[ ] And add it to our router in app.routes.ts

import { LoginComponent } from './login';

{ path: 'login', component: LoginComponent },

[ ] And add that router link to our menu

<a class="ui item" routerLink="/login" routerLinkActive="active">

[ ] Demonstrate the login page

[ ] Now create a rough login form

<form class="ui form error">
  <div class="field">
    <label>User Name</label>
    <input name="username" placeholder="User Name" type="text" required >
  </div>
  <div class="field">
    <label>Password</label>
    <input name="password" placeholder="Password" type="password">
  </div>
  <div class="field">
    <div class="ui checkbox">
      <input name="rememberme" tabindex="0" type="checkbox">
      <label>Remember Me</label>
    </div>
  </div>
  <button class="ui button primary" type="submit">Submit</button>
</form>

[ ] Now we’re going to use the ngForm module to do magic in creating a form backing model (not our domain model!)

<form class="ui form error" #form="ngForm"

[ ] Add ngModel to each input field

[ ] Add a pipe to see the data in action

{{ form.value | json }}

[ ] Handle the form values in OnSubmit()

(ngSubmit)='OnSubmit(form.value)'

 OnSubmit(formJson) {
    console.log(formJson);
  }

[ ] Let’s look at the form model for validation

<input #username='ngModel' ...> 

 <div *ngIf='username.invalid && username.dirty' class="ui error message"><p>Username is a required field</p></div>

[ ] You can also structure JSON, and do validity checking on whole groups (eg an address)

ngModelGroup='blah'

[ ] Celebrate the win of template-driven forms

[ ] Tomorrow we’ll tackle reactive forms