Create a Signup Form Using Reactive Forms in Angular
A signup form looks simple until you add the details users expect: clear error messages, a password that has to meet some rules, a confirm-password field that must match, and a submit button that doesn't let half-filled data through. This guide builds that form step by step with Angular Reactive Forms, including a cross-field validator that compares the two password fields properly.
We'll build:
- A signup form with name, email, password and confirm password
- Built-in validators for required fields, email format and minimum length
- A password strength rule using a pattern
- A password match validator applied to the whole form group
- Error messages that appear only after the user has touched a field
- A show/hide password toggle
The code uses Angular 17+ with standalone components and the new @if template syntax. If your project still uses NgModule, see the note in Step 1.
Step 1 : Create the Signup Component
Generate a standalone component:
ng generate component signup
Reactive Forms need ReactiveFormsModule. In a standalone component, import it directly in the component's imports array (we'll do that in Step 3).
Using NgModule? Add ReactiveFormsModule to the imports of the module that declares SignupComponent instead. Everything else in this guide stays the same.
Step 2 : Write the Password Match Validator
Comparing two fields is a cross-field check, so the validator must run on the form group, not on a single control. A validator attached to confirmPassword alone only sees its own value and can't read the password field reliably.
Create password-match.validator.ts:
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export function passwordMatchValidator(
passwordKey = 'password',
confirmKey = 'confirmPassword'
): ValidatorFn {
return (group: AbstractControl): ValidationErrors | null => {
const password = group.get(passwordKey)?.value;
const confirm = group.get(confirmKey)?.value;
// Don't report a mismatch until both fields have a value
if (!password || !confirm) {
return null;
}
return password === confirm ? null : { passwordMismatch: true };
};
}
The validator returns { passwordMismatch: true } on the group. That matters: an older pattern you'll see online calls control.get('confirmPassword').setErrors({ mismatch: true }) inside the validator. That overwrites any other errors on the field (such as required) and never clears itself properly, which leads to forms that stay invalid after the user fixes the password.
Step 3 : Build the Form in the Component
Open signup.component.ts:
import { Component, inject, signal } from '@angular/core';
import { FormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { passwordMatchValidator } from './password-match.validator';
type SignupField = 'name' | 'email' | 'password' | 'confirmPassword';
@Component({
selector: 'app-signup',
standalone: true,
imports: [ReactiveFormsModule],
templateUrl: './signup.component.html',
styleUrl: './signup.component.css'
})
export class SignupComponent {
private fb = inject(FormBuilder);
showPassword = signal(false);
submitted = signal(false);
// At least 8 characters, one letter and one number
private strongPassword = /^(?=.*[A-Za-z])(?=.*\d).{8,}$/;
form = this.fb.nonNullable.group(
{
name: ['', [Validators.required, Validators.minLength(2)]],
email: ['', [Validators.required, Validators.email]],
password: ['', [Validators.required, Validators.pattern(this.strongPassword)]],
confirmPassword: ['', Validators.required]
},
{ validators: passwordMatchValidator() }
);
get f() {
return this.form.controls;
}
showError(name: SignupField): boolean {
const control = this.form.controls[name];
return control.invalid && (control.touched || this.submitted());
}
get mismatch(): boolean {
return (
this.form.hasError('passwordMismatch') &&
(this.f.confirmPassword.touched || this.submitted())
);
}
onSubmit(): void {
this.submitted.set(true);
if (this.form.invalid) {
this.form.markAllAsTouched();
return;
}
const { name, email, password } = this.form.getRawValue();
console.log('Signup data', { name, email, password });
// Call your API here, then reset:
this.form.reset();
this.submitted.set(false);
}
}
A few things worth pointing out:
fb.nonNullable.groupgives you typed controls whose values are nevernull, sogetRawValue()returns plain strings.- The group-level validator goes in the second argument as
{ validators: ... }. Older code uses{ validator: ... }(singular), which is deprecated. showError()keeps error messages hidden until the user has left the field or pressed submit, so the form doesn't start out covered in red.
Step 4 : Create the HTML Template
Open signup.component.html:
<form [formGroup]="form" (ngSubmit)="onSubmit()" novalidate class="signup">
<h2>Create your account</h2>
<label for="name">Full name</label>
<input id="name" type="text" formControlName="name" autocomplete="name" />
@if (showError('name')) {
<small class="error">Enter your name (at least 2 characters).</small>
}
<label for="email">Email</label>
<input id="email" type="email" formControlName="email" autocomplete="email" />
@if (showError('email')) {
<small class="error">
@if (f.email.hasError('required')) { Email is required. }
@else { Enter a valid email address. }
</small>
}
<label for="password">Password</label>
<div class="password-row">
<input id="password" [type]="showPassword() ? 'text' : 'password'"
formControlName="password" autocomplete="new-password" />
<button type="button" (click)="showPassword.set(!showPassword())">
{{ showPassword() ? 'Hide' : 'Show' }}
</button>
</div>
@if (showError('password')) {
<small class="error">Use at least 8 characters, including a letter and a number.</small>
}
<label for="confirmPassword">Confirm password</label>
<input id="confirmPassword" [type]="showPassword() ? 'text' : 'password'"
formControlName="confirmPassword" autocomplete="new-password" />
@if (showError('confirmPassword')) {
<small class="error">Please confirm your password.</small>
} @else if (mismatch) {
<small class="error">Passwords don't match.</small>
}
<button type="submit">Sign up</button>
</form>
The mismatch message reads the error from the form (form.hasError('passwordMismatch')), because that's where the validator puts it. Both password fields share one show/hide toggle so users can check what they typed.
Notice the submit button is not disabled while the form is invalid. Disabling it hides the reason the user can't continue; letting them press it and then showing every error is clearer.
Step 5 : Add Basic Styling
Add this to signup.component.css:
.signup {
display: grid;
gap: 6px;
max-width: 420px;
}
.signup label {
margin-top: 12px;
font-weight: 600;
}
.signup input {
padding: 10px 12px;
border: 1px solid #c9d1dc;
border-radius: 8px;
font-size: 15px;
}
.signup input.ng-invalid.ng-touched {
border-color: #d14343;
}
.password-row {
display: flex;
gap: 8px;
}
.password-row input {
flex: 1;
}
.error {
color: #d14343;
}
.signup button[type="submit"] {
margin-top: 18px;
padding: 12px;
border: 0;
border-radius: 8px;
background: #0a2d5a;
color: #fff;
font-weight: 600;
cursor: pointer;
}
Angular adds the ng-invalid and ng-touched classes automatically, so the red border only appears on fields the user has visited.
Step 6 : Test It
Run ng serve and try these cases:
- Press Sign up on the empty form: every required field shows its message.
- Type
abcas the email: "Enter a valid email address" appears when you leave the field. - Type
passwordas the password: the strength message appears, because there's no number. - Type
secret123andsecret124: "Passwords don't match" appears. - Fix the confirm field: the mismatch message disappears and the form becomes valid.
Common Issues
The mismatch error never shows. The validator is probably on the confirmPassword control instead of the group, or the template is checking f.confirmPassword.hasError('passwordMismatch'). The error lives on the form: use form.hasError('passwordMismatch').
The form stays invalid after the passwords match. This happens with the setErrors() approach on the child control. Switch to returning the error from the group validator as shown in Step 2.
Can't bind to 'formGroup' since it isn't a known property of 'form'. ReactiveFormsModule isn't imported in the standalone component (or in the NgModule that declares it).
The mismatch check runs too late or too often. Group validators run whenever any child value changes. If you want validation only when the user leaves a field, add { validators: passwordMatchValidator(), updateOn: 'blur' }.
Summary
For a dependable signup form with Reactive Forms:
- Use built-in validators for required fields, email and length, and
Validators.patternfor password rules. - Put cross-field checks like password matching on the form group and return an error object instead of calling
setErrors(). - Show errors only after a field is touched or the form is submitted.
- Use
fb.nonNullablefor typed, non-null values.
Next, you can protect the pages behind this signup with Angular route guards, or connect it to Firebase Authentication.
0 Comments