Back to course

Template-Driven Forms (TDF) Setup

The Complete Angular Developer: From Zero to Hero

42. Template-Driven Forms (TDF) Setup

Template-Driven Forms rely heavily on directives placed directly in the HTML template to infer the form model. This approach is quick and easy for simple forms.

Key Directives in TDF

  1. NgForm: Automatically applied to the <form> tag. It manages the whole form structure and state.
  2. ngModel: Automatically creates a FormControl instance for the input element and binds it to a component property using two-way binding [(ngModel)].

Step-by-Step TDF Creation

1. Ensure FormsModule is Imported (See previous lesson).

2. Define the Form in the Template

We use a template reference variable (#f) to access the NgForm directive instance, allowing us to inspect the form's state.

html

<p *ngIf="usernameCtrl.invalid && usernameCtrl.touched" class="error-message">
  Username is required.
</p>

<button type="submit" [disabled]="f.invalid">Submit

3. Handle Submission in the Component

typescript import { NgForm } from '@angular/forms';

export class TdfComponent { user = { username: '', email: '' };

onSubmit(form: NgForm) { if (form.valid) { console.log('Form Submitted!', this.user); // Send this.user data to the service } else { console.error('Form is invalid.'); } } }

In TDF, the component only holds the data model (user), while the template manages the controls and validation state.