Welcome back, coders! Today, we're diving into the world of Template-Driven Forms in Angular. If you're new to Angular, don't worry! We'll start from the basics and work our way up.
Template-Driven Forms are a way to create forms in Angular by using the ngTemplateOutlet and ngFor directives. They are simple to set up and offer more control over form behavior compared to Reactive Forms.
Let's create a simple form to get started:
<!-- app.component.html -->
<form #myForm="ngForm">
<label for="name">Name:</label>
<input type="text" name="name" [(ngModel)]="name" required>
<br>
<label for="email">Email:</label>
<input type="email" name="email" [(ngModel)]="email" required>
<br>
<button type="submit">Submit</button>
</form>In this example, #myForm is a reference to our form and [(ngModel)] creates a two-way data binding between the form control and the component property.
Form validation in Template-Driven Forms can be achieved by using the ngModel directive's valid and invalid properties:
<!-- app.component.html -->
<div *ngIf="myForm.invalid">
Please fill out the form correctly.
</div>You can also validate individual controls by adding the ngClass directive to apply CSS classes for valid and invalid states:
<!-- app.component.html -->
<label for="name" *ngIf="name.invalid && name.touched">
Name is required.
</label>To handle form submission, we can use the ngSubmit directive:
<!-- app.component.html -->
<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)">
<!-- ... -->
</form>
<!-- app.component.ts -->
onSubmit(form: NgForm) {
console.log(form.value);
}Which directive is used to create a Template-Driven Form?
We hope you enjoyed this lesson on Template-Driven Forms in Angular! In the next lesson, we'll explore more advanced concepts and practical examples to help you become proficient in Angular form development. Stay tuned! 😄