Skip to content

Instantly share code, notes, and snippets.

@killerchip
Created January 1, 2018 06:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save killerchip/d314cfbd4a87ceb698f3c72a565dd17a to your computer and use it in GitHub Desktop.
Save killerchip/d314cfbd4a87ceb698f3c72a565dd17a to your computer and use it in GitHub Desktop.
Angular cheatsheet: Template driven forms

Template Driven Forms

How to setup

import FormsModule

import { FormsModule } from '@angular/forms';
  
@NgModule ({
  ...
  imports: [
    FormsModule,
    ...
  ]
})

Add Form and submit handling HTML Template:

<form #myForm="ngForm"
  (submit)="handleSubmit(myForm.value)"
>
<button type="submit">Submit</button>
</form>

Component:

  public handleSubmit(formValue: any) {
    console.log(formValue);
  }

Add Fields

<div>
    <label for="usernameInput">Username</label>
    <input type="text"
      id="usernameInput"
      name="username"
      ngModel
      placeholder="enter username"
    >
  </div>  

Available form properties

  • myForm.errors
  • myForm.dirty
  • myForm.valid

Notes and Explanations

  • NgForm automatically binds to a <form> element and creates a FormGroup object called ngForm. With #myForm="ngForm" we actually grab this FormGroup object and bind it to a template variable.

  • NgForm automatically creates the (submit) event emitter.

  • NgModel directive creates automatically a FormControl named with the name value.

  • NgModel creates a one-way data bind (model -> view)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment