AI Hints
Home›Angular Tutorial›Forms in Angular, Template-Driven Forms and Reactive Forms
Angular · Lesson 83 of 120

Template-Driven Forms

NgModel.

⏱ 2 min read▶ Video at 1:39:07🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

The quickest way to connect an input to our data is ng model. It works right in the template.

  • The quickest way
  • Input ↔ data
  • ngModel

ngModel

Import forms module. Then banana in a box, with ng model, binds an input to a signal, both ways. Typing changes the signal. And changing the signal changes the input.

keyvalue
imports: [FormsModule]enable it
[(ngModel)]="name"two-way binding
Typingupdates the signal
The signalupdates the input

Two-way binding

Name, and copies, are signals. Each input is bound to one, with ng model. The last line reads them. We type Sam, and change copies to three. Run it. The sentence followed every key press.

app.tstypescript
import { Component, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-root',
  imports: [FormsModule],
  template: `
    <p><input [(ngModel)]="name" placeholder="Your name"></p>
    <p>Copies <input type="number" [(ngModel)]="copies"></p>
    <p>{{ name() || 'Someone' }} wants {{ copies() }} copies of Emma.</p>
  `,
})
export class App {
  name = signal('');
  copies = signal(1);
}
Also uses actions.json
[{"type": "input", "text": "Sam"}, {"clear": "input[type=number]"}, {"type": "input[type=number]", "text": "3"}]

A whole form

Hash f, equals ng form, gives us the form itself. Required, and email, are validation rules, on the input. The button is disabled while the form is invalid. On submit, f dot value holds every field. We type an email, and subscribe. Run it. The form became valid, and send received the email.

app.tstypescript
import { Component, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-root',
  imports: [FormsModule],
  template: `
    <form #f="ngForm" (ngSubmit)="send(f.value)">
      <input name="email" ngModel required email placeholder="Email">
      <button [disabled]="f.invalid">Subscribe</button>
      <p>Form valid: {{ f.valid }}</p>
    </form>
    <p>{{ message() }}</p>
  `,
})
export class App {
  message = signal('');
  send(v: { email: string }) { this.message.set(`Subscribed: ${v.email}`); }
}
Also uses actions.json
[{"type": "input", "text": "sam@example.com"}, {"click": "button"}]

Summary

Ng model binds inputs to signals, and ng form tracks the whole form, with simple rules like required. Next, reactive forms.

Key takeaways
  • [(ngModel)]
  • #f="ngForm"
  • required, email
Next up: Reactive Forms — forms in the class