Template-Driven Forms
The most straightforward approach to building forms in Angular is to take advantage of the directives provided for you.
First, consider a typical form:
1
<form method="POST" action="/register" id="signup-form">
2
<label for="email">Email</label>
3
<input type="text" name="email" id="email">
4
5
<label for="password">Password</label>
6
<input type="password" name="password" id="password">
7
8
<button type="submit">Sign Up</button>
9
</form>
Copied!
Angular has already provided you a form directive, and form related directives such as input, etc which operates under the covers. For a basic implementation, we just have to add a few attributes and make sure our component knows what to do with the data.
index.html
1
<signup-form>Loading...</signup-form>
Copied!
signup-form.component.html
1
<form #signupForm="ngForm" (ngSubmit)="registerUser(signupForm)">
2
<label for="email">Email</label>
3
<input type="text" name="email" id="email" ngModel>
4
5
<label for="password">Password</label>
6
<input type="password" name="password" id="password" ngModel>
7
8
<button type="submit">Sign Up</button>
9
</form>
Copied!
signup-form.component.ts
1
import { Component } from '@angular/core';
2
import { NgForm } from '@angular/forms';
3
4
@Component({
5
selector: 'app-signup-form',
6
templateUrl: 'app/signup-form.component.html',
7
})
8
export class SignupFormComponent {
9
registerUser(form: NgForm) {
10
console.log(form.value);
11
// {email: '...', password: '...'}
12
// ...
13
}
14
}
Copied!
Last modified 2yr ago
Copy link