Template-driven forms in Angular
In this lesson, we’ll start by discussing forms. Angular provides two ways to work with forms — template-driven and reactive forms. Today, we’ll focus on the template-driven approach.
Template-driven form connects a component class property with an input field using two-way data binding. Two-way binding is a mechanism that synchronizes data between the model (component class) and the view (component template).
To bind data to an input field, you need to add the ngModel attribute to the input element (see code example below). Each field corresponds to a specific class property. To submit the form, add the (ngSubmit) event to the form element.
In real projects, your forms can contain many fields. So when submitting a form, it’s useful to use the ngForm directive, which is essentially a form instance containing all form values and other useful properties (for example, the form’s validation state). You can read more about NgForm on the Angular website.
In addition, many fields can depend on each other (for example, the zip code format may depend on the selected country). You need to manage these field dependencies, which can be cumbersome. For such complex forms, it’s more convenient to use reactive forms, which we’ll discuss in the next lesson.
app.ts
import {Component} from '@angular/core';
import {NgForm} from '@angular/forms';
@Component({
selector: 'app-root',
imports: [
],
templateUrl: './app.html',
styleUrl: './app.scss'
})
export class App {
protected login = '';
protected password = '';
protected selectedRole = 'guest';
protected roles = ['admin', 'guest'];
protected submitForm(form: NgForm) {
console.log(form.value);
console.log('form is valid: ', form.valid);
}
}
app.html
<form (ngSubmit)="submitForm(loginForm)" #loginForm="ngForm">
<div>
<label for="login">Login</label>
<input required type="text" id="login" name="login" [(ngModel)]="login">
</div>
<div>
<label for="password">Password</label>
<input type="password" id="password" name="password" [(ngModel)]="password">
</div>
<div>
<select name="role" [(ngModel)]="selectedRole">
@for (role of roles; track role) {
<option>{{role}}</option>
}
</select>
</div>
<button [disabled]="!loginForm.valid">Login</button>
</form>
0 Comments