> For the complete documentation index, see [llms.txt](https://briebug.gitbook.io/angular-fundamentals/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://briebug.gitbook.io/angular-fundamentals/template-driven-forms.md).

# Template Driven Forms

## What are template driven forms?

* Usually use ngModel
* Validation rules imbedded in HTML
* Can require end to end testing
* Works well for small projects/forms with simple validation

## Import Forms Module

Template driven forms requires the `FormsModule` for directives like `ngModel`. Since this is usually used across multiple forms, it's usually imported in the app.module.

{% code title="app.module.ts" %}

```typescript
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';


@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent, LoginComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

```

{% endcode %}

## Creating a template driven form

If you don't have a `LoginComponent` create one using `ng g c login`

{% code title="login.component.html" %}

```markup
<form #loginForm="ngForm" (ngSubmit)="submit(loginForm)">
  <h1>Login</h1>
  <p>
    <label>User Name: </label>
    <input type="text" name="username" [(ngModel)]="user.username" />
  </p>
  <p>
    <label>
      Password: </label>
    <input type="password" name="password" [(ngModel)]="user.password" />
  </p>
  <input type="submit" value="Submit" />
  <p class="message">{{message}}</p>
</form>
```

{% endcode %}

The form tag has a template variable declared using `#loginForm` which points to the `ngForm` directive. The submit button is of type submit and the form will call the submit function and pass the form to it.

## Template Driven Component

{% embed url="<https://stackblitz.com/edit/angular-fundamentals-ad2019-9?file=src%2Fapp%2Flogin%2Flogin.component.ts&view=editor>" %}

Enter a username, password, and click the submit button. The console should log a similar message: `form submitted:{"username":"jesse.sanders@briebug.com","password":"mySecretPassword"}`

## Setting Required Fields - HTML5 Validation

By adding the required attribute to each input, we can activate the HTML5 validation

```markup
<input type="text" name="username" [(ngModel)]="user.username" required />
```

{% hint style="warning" %}
Warning: since Angular version 4, you must add `ngNativeValidate` for HTML 5 validation to fire.
{% endhint %}

## Why Angular validation?

* Control when validation messages appear
* Customize validation messages
* Complex/programatic validation
* Custom validators

## Angular Built-In Validators

* required
* minLength
* maxLength
* pattern

## Adding Validation messages

`ngModel` keeps track of each controls validity. Has properties including valid, invalid, touched, untouched, pristine, dirty

{% embed url="<https://stackblitz.com/edit/angular-fundamentals-ad2019-9dot5?file=src%2Fapp%2Flogin%2Flogin.component.html&view=editor>" %}

## Controlling When Validation Messages Appear

By default, validation messages appear immediately We can control when the messages appear by using the `ngModelOptions` or `ngFormOptions` directive. Usage: `<input [ngModelOptions]="{ updateOn: 'blur' }" ... />` or `<form [ngFormOptions]="{ updateOn: 'submit' }" ... >`

* blur - validate when the control loses focus
* submit - validate when the form is submitted
* change (default) - validate after every keystroke
* Use custom variable

## Display Form Validation State

{% embed url="<https://stackblitz.com/edit/angular-fundamentals-ad2019-9dot6?file=src%2Fapp%2Flogin%2Flogin.component.html>" %}

## Display Field Validation State

{% embed url="<https://stackblitz.com/edit/angular-fundamentals-ad2019-9dot7?file=src%2Fapp%2Flogin%2Flogin.component.html&view=editor>" %}

## Adding Validation Classes

{% code title="login.component.css" %}

```css
input.ng-invalid {
  border: 1px solid red;
}

input.ng-valid {
  border: 1px solid blue;
}

input.ng-pristine {
  background-color: lightgrey;
}
```

{% endcode %}

{% hint style="info" %}
Validation indicators can be great visual cues to users
{% endhint %}

## Other Control Examples

{% embed url="<https://stackblitz.com/edit/angular-fundamentals-ad2019-9dot9?file=src%2Fapp%2Fregistration%2Fregistration.component.html&view=editor>" %}

## Summary

* What are template driven forms?
* Import FormsModule
* Creating a template driven form/component
* HTML5 Validation
* Why Angular Validators
* Angular Built-In Validators
* Adding Validation Messages and when they show
* Displaying Form and Field Validation Statuses
* Validation Classes
* Validating Other Controls
