How to create a form in Angular 14 with validation
First, in your component HTML file, you can create a form using the form
and input
tags. In this example, we will create a simple login form with two
inputs: email and password. We will also add some validation rules to
ensure that the user enters a valid email address and that the password
is at least 8 characters long:
<form #loginForm="ngForm" (ngSubmit)="submitLoginForm()">
<div>
<label>Email:</label>
<input type="email" name="email" ngModel required email>
<div *ngIf="loginForm.controls.email.errors?.required">
Email is required.
</div>
<div *ngIf="loginForm.controls.email.errors?.email">
Email is invalid.
</div>
</div>
<div>
<label>Password:</label>
<input type="password" name="password" ngModel minlength="8" required>
<div *ngIf="loginForm.controls.password.errors?.required">
Password is required.
</div>
<div *ngIf="loginForm.controls.password.errors?.minlength">
Password must be at least 8 characters long.
</div>
</div>
<button type="submit" [disabled]="!loginForm.valid">Login</button>
</form>
In this code, we are using Angular's built-in ngForm
directive to bind the form to a local variable loginForm
. We are also using Angular's ngModel
directive to bind the values of the email and password inputs to properties of the loginForm
variable. We have also added the required
and email
validators to the email input and the minlength
validator to the password input.
Next, in your component TypeScript file, you can define the form submission function that is called when the user clicks the "Login" button:
import { Component } from '@angular/core';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent {
submitLoginForm() {
// Handle form submission here
}
}
In this code, we are defining a submitLoginForm
function that will handle the form submission. You can add your own code to this function to handle the login process.
That's it! This is a basic example of how to create a form with validation in Angular 14. Of course, you can customize the validation rules and form behavior to fit your needs.
Comments
Post a Comment