Template-Driven Forms
- Template-driven forms are a great starting point for developers new to Angular. They are created using directives in the HTML template.
Example:
Step 1: Create an Angular project using Angular CLI.
ng new angular-forms
Step 2: Create a new component message
ng g c form-component
Step 3: Now create the form in the ‘form-component.component.html’.
<div class="container">
<h2>Template-Driven Form</h2>
<form #login="ngForm" (ngSubmit)="submit(login)">
<div class="form-group">
<label for="fname">First Name:</label><br />
<input type="text" name="fname" class="form-control" [(ngModel)]="user.fname">
</div>
<pre></pre>
<div class="form-group">
<label for="lname">Last Name:</label><br />
<input type="text" name="lname" class="form-control" [(ngModel)]="user.lname">
</div>
<pre></pre>
<div class="form-group">
<label for="email">Email:</label><br />
<input type="email" name="email" class="form-control" [(ngModel)]="user.email">
</div>
<pre></pre>
<div class="form-group">
<label for="password">Password:</label><br />
<input type="password" name="password" class="form-control" [(ngModel)]="user.password">
</div>
<pre></pre>
<button class="btn btn-primary" type="submit">Submit</button>
</form>
</div>
Step 4: Edit the 'form-component.component.ts' to define the function and attributes.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-form-component',
templateUrl: './form-component.component.html',
styleUrls: ['./form-component.component.css']
})
export class FormComponentComponent {
user = {
fname: '',
lname: '',
email: '',
password: ''
}
submit(login) {
console.log("form submitted", this.user)
}
}
Step 5: Add CSS to ‘form-component.component.css’ for better styling.
div {
text-align: center;
}
label {
text-align: left;
}
Step 6: Add the ‘<app-form-component></app-form-component>’ to the ‘app.component.html’ to include the ‘Form-Component’ in the main application. Also, add the FormsModule in ‘app.module.ts’.
<app-form-component></app-form-component>
Step 7: Now run or compile the application.
ng serve
You will see the result on http://localhost:4200