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
NgForm: Automatically applied to the<form>tag. It manages the whole form structure and state.ngModel: Automatically creates aFormControlinstance 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
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.