English
Sign-in and registration
Step 1. A layout with content projection
Why. The sign-in and registration pages share their frame: a centred card under the Chatex logo, a heading and a subheading. A layout component holds the frame, and each page fills it.
Do. Create the layout:
angular-ts
import { ChangeDetectionStrategy, Component, input } from '@angular/core';
import { ICONS } from '../../shared/ui/icons';
/** Centred card used by the sign-in and register pages. */
@Component({
selector: 'app-auth-layout',
imports: [ICONS],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<main
class="flex min-h-dvh items-start justify-center bg-gradient-to-br from-brand-50 via-canvas to-canvas px-4 py-10 sm:items-center dark:from-brand-950/40"
>
<div class="w-full max-w-md">
<div class="mb-8 flex flex-col items-center gap-3 text-center">
<span
class="flex size-14 items-center justify-center rounded-2xl bg-brand-600 text-white shadow-lg shadow-brand-600/30"
>
<svg lucideMessagesSquare class="size-7"></svg>
</span>
<h1 class="text-2xl font-bold tracking-tight">{{ heading() }}</h1>
<p class="text-sm text-muted">{{ subheading() }}</p>
</div>
<div class="card p-6 shadow-sm sm:p-8">
<ng-content />
</div>
</div>
</main>
`,
})
export class AuthLayout {
readonly heading = input.required<string>();
readonly subheading = input('');
}input.required<string>()declares a required input — a parameter that the parent sets in its template (heading="Welcome back"). An input is a read-only signal: the template readsheading().input('')declares an optional one with a default value. The compiler checks that every use of<app-auth-layout>setsheading.<ng-content />marks where the content between<app-auth-layout>and</app-auth-layout>appears — content projection, the counterpart of@Bodyin a Razor layout orChildContentin a Blazor component.- The double curly braces in the template are interpolation: they insert the value of an expression as text, HTML-escaped. Angular never interprets interpolated text as markup, which protects against cross-site scripting.
Step 2. The sign-in page and Reactive Forms
Why. Angular has two form APIs. Template-driven forms bind inputs to fields with ngModel and keep the logic in the template. Reactive Forms build the form model in the class — controls, validators, values — and bind the template to it. The model is typed, testable without a DOM and easy to reset or fill from code, which is why Chatex uses Reactive Forms everywhere.
Do. Create the page:
angular-ts
import { ChangeDetectionStrategy, Component, inject, input, signal } from '@angular/core';
import { NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { Router, RouterLink } from '@angular/router';
import { problemMessage } from '../../core/api/problem';
import { AuthService } from '../../core/auth/auth.service';
import { ICONS } from '../../shared/ui/icons';
import { AuthLayout } from './auth-layout';
@Component({
selector: 'app-login-page',
imports: [ReactiveFormsModule, RouterLink, AuthLayout, ICONS],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<app-auth-layout heading="Welcome back" subheading="Sign in to continue to Chatex">
<form [formGroup]="form" (ngSubmit)="submit()" class="space-y-4" novalidate>
@if (error()) {
<p
class="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700 dark:bg-red-950 dark:text-red-300"
role="alert"
>
{{ error() }}
</p>
}
<div>
<label class="label" for="login">User name or email</label>
<input
id="login"
class="input"
formControlName="login"
autocomplete="username"
autocapitalize="none"
[class.input-invalid]="invalid('login')"
/>
@if (invalid('login')) {
<p class="field-error">Enter your user name or email.</p>
}
</div>
<div>
<label class="label" for="password">Password</label>
<input
id="password"
class="input"
type="password"
formControlName="password"
autocomplete="current-password"
[class.input-invalid]="invalid('password')"
/>
@if (invalid('password')) {
<p class="field-error">Enter your password.</p>
}
</div>
<button type="submit" class="btn-primary w-full" [disabled]="busy()">
@if (busy()) {
<svg lucideLoaderCircle class="size-4 animate-spin"></svg>
}
Sign in
</button>
</form>
<p class="mt-6 text-center text-sm text-muted">
New to Chatex?
<a
routerLink="/register"
[queryParams]="returnUrl() ? { returnUrl: returnUrl() } : {}"
class="font-medium text-brand-600 hover:underline dark:text-brand-400"
>Create an account</a
>
</p>
</app-auth-layout>
`,
})
export class LoginPage {
private readonly auth = inject(AuthService);
private readonly router = inject(Router);
readonly returnUrl = input<string>();
protected readonly busy = signal(false);
protected readonly error = signal<string | null>(null);
protected readonly form = inject(NonNullableFormBuilder).group({
login: ['', Validators.required],
password: ['', Validators.required],
});
protected invalid(name: 'login' | 'password'): boolean {
const control = this.form.controls[name];
return control.invalid && control.touched;
}
protected async submit(): Promise<void> {
if (this.form.invalid) {
this.form.markAllAsTouched();
return;
}
this.busy.set(true);
this.error.set(null);
try {
const { login, password } = this.form.getRawValue();
await this.auth.login({ login: login.trim(), password });
await this.router.navigateByUrl(safeReturnUrl(this.returnUrl()));
} catch (error) {
this.error.set(problemMessage(error));
} finally {
this.busy.set(false);
}
}
}
/** Only follow in-app paths, never another origin. */
export function safeReturnUrl(url: string | undefined): string {
return url && url.startsWith('/') && !url.startsWith('//') ? url : '/chats';
}inject(NonNullableFormBuilder).group({ … })builds aFormGroupwith twoFormControl<string>s. Non-nullable means thatreset()returns a control to its initial value'', not tonull, so the value type staysstring.Validators.requiredis a built-in validator; the form isinvalidwhile any validator fails.[formGroup]="form"andformControlName="login"bind the HTML form and its inputs to the model;ReactiveFormsModuleinimportsprovides these directives. Forgetting it fails the build withNG8002: Can't bind to 'formGroup' since it isn't a known property of 'form'.(ngSubmit)="submit()"is an event binding: parentheses listen, square brackets bind a property.novalidateswitches off the browser's own validation bubbles in favour of ours.invalid(name)shows a field's message only after the user has touched it (left it once) — not while they are still typing the first character.submit()marks all fields touched when the form is invalid, so a click on "Sign in" with empty fields shows both messages.busyanderrorare signals; the button is disabled and shows a spinner while the request runs, and the error fromproblemMessageappears above the form ("Wrong user name, email or password.").returnUrl = input<string>()receives the query parameter?returnUrl=thatauthGuardadded, thanks towithComponentInputBinding()of topic 16. The link to the registration page passes it on with[queryParams].safeReturnUrlfollows only paths of this application. A URL from a query string is attacker-controlled:?returnUrl=https://evil.examplemust not turn the sign-in page into an open redirect. A path must start with/but not with//, which browsers read as another host.
Step 3. Registration with server field errors
Why. The registration form repeats the server's rules (topic 8) so that most mistakes are caught before a request: a user name of 3–32 letters, digits and _ starting with a letter, a valid email, a password of at least 8 characters with a digit. Some errors can only come from the server — the user name or the email is taken — and they must appear under the right field, not as a general message.
Do. Create the page:
angular-ts
import { ChangeDetectionStrategy, Component, inject, input, signal } from '@angular/core';
import { NonNullableFormBuilder, ReactiveFormsModule, Validators } from '@angular/forms';
import { Router, RouterLink } from '@angular/router';
import { fieldErrors, problemMessage, toProblem } from '../../core/api/problem';
import { AuthService } from '../../core/auth/auth.service';
import { ICONS } from '../../shared/ui/icons';
import { AuthLayout } from './auth-layout';
import { safeReturnUrl } from './login.page';
type Field = 'displayName' | 'userName' | 'email' | 'password';
/** Mirrors the server rules so most mistakes are caught before submitting. */
export const USER_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9_]*$/;
export const PASSWORD_PATTERN = /\d/;
@Component({
selector: 'app-register-page',
imports: [ReactiveFormsModule, RouterLink, AuthLayout, ICONS],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<app-auth-layout heading="Create your account" subheading="It takes less than a minute">
<form [formGroup]="form" (ngSubmit)="submit()" class="space-y-4" novalidate>
@if (error()) {
<p
class="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-700 dark:bg-red-950 dark:text-red-300"
role="alert"
>
{{ error() }}
</p>
}
<div>
<label class="label" for="displayName">Display name</label>
<input
id="displayName"
class="input"
formControlName="displayName"
autocomplete="name"
maxlength="64"
[class.input-invalid]="message('displayName')"
/>
@if (message('displayName'); as m) {
<p class="field-error">{{ m }}</p>
}
</div>
<div>
<label class="label" for="userName">User name</label>
<div class="relative">
<span class="pointer-events-none absolute top-1/2 left-3 -translate-y-1/2 text-muted"
>@</span
>
<input
id="userName"
class="input pl-7"
formControlName="userName"
autocomplete="username"
autocapitalize="none"
maxlength="32"
[class.input-invalid]="message('userName')"
/>
</div>
@if (message('userName'); as m) {
<p class="field-error">{{ m }}</p>
} @else {
<p class="mt-1 text-xs text-muted">
3–32 characters: letters, digits and _. Starts with a letter.
</p>
}
</div>
<div>
<label class="label" for="email">Email</label>
<input
id="email"
class="input"
type="email"
formControlName="email"
autocomplete="email"
[class.input-invalid]="message('email')"
/>
@if (message('email'); as m) {
<p class="field-error">{{ m }}</p>
}
</div>
<div>
<label class="label" for="password">Password</label>
<input
id="password"
class="input"
type="password"
formControlName="password"
autocomplete="new-password"
[class.input-invalid]="message('password')"
/>
@if (message('password'); as m) {
<p class="field-error">{{ m }}</p>
} @else {
<p class="mt-1 text-xs text-muted">At least 8 characters, including a digit.</p>
}
</div>
<button type="submit" class="btn-primary w-full" [disabled]="busy()">
@if (busy()) {
<svg lucideLoaderCircle class="size-4 animate-spin"></svg>
}
Create account
</button>
</form>
<p class="mt-6 text-center text-sm text-muted">
Already have an account?
<a
routerLink="/login"
[queryParams]="returnUrl() ? { returnUrl: returnUrl() } : {}"
class="font-medium text-brand-600 hover:underline dark:text-brand-400"
>Sign in</a
>
</p>
</app-auth-layout>
`,
})
export class RegisterPage {
private readonly auth = inject(AuthService);
private readonly router = inject(Router);
readonly returnUrl = input<string>();
protected readonly busy = signal(false);
protected readonly error = signal<string | null>(null);
private readonly serverErrors = signal<Partial<Record<Field, string>>>({});
protected readonly form = inject(NonNullableFormBuilder).group({
displayName: ['', [Validators.required, Validators.maxLength(64)]],
userName: [
'',
[
Validators.required,
Validators.minLength(3),
Validators.maxLength(32),
Validators.pattern(USER_NAME_PATTERN),
],
],
email: ['', [Validators.required, Validators.email, Validators.maxLength(256)]],
password: [
'',
[
Validators.required,
Validators.minLength(8),
Validators.maxLength(128),
Validators.pattern(PASSWORD_PATTERN),
],
],
});
constructor() {
// A server error for a field goes away as soon as the user edits that field.
for (const name of Object.keys(this.form.controls) as Field[]) {
this.form.controls[name].valueChanges.subscribe(() =>
this.serverErrors.update((e) => ({ ...e, [name]: undefined })),
);
}
}
protected message(name: Field): string | null {
const server = this.serverErrors()[name];
if (server) {
return server;
}
const control = this.form.controls[name];
if (!control.touched || control.valid) {
return null;
}
const e = control.errors ?? {};
if (e['required']) return 'This field is required.';
if (name === 'userName') {
if (e['minlength']) return 'At least 3 characters.';
if (e['pattern']) return 'Start with a letter; use only letters, digits and _.';
}
if (name === 'email') return 'Enter a valid email address.';
if (name === 'password') {
if (e['minlength']) return 'At least 8 characters.';
if (e['pattern']) return 'Include at least one digit.';
}
if (e['maxlength']) return 'Too long.';
return 'Invalid value.';
}
protected async submit(): Promise<void> {
if (this.form.invalid) {
this.form.markAllAsTouched();
return;
}
this.busy.set(true);
this.error.set(null);
try {
const value = this.form.getRawValue();
await this.auth.register({
displayName: value.displayName.trim(),
userName: value.userName.trim(),
email: value.email.trim(),
password: value.password,
});
await this.router.navigateByUrl(safeReturnUrl(this.returnUrl()));
} catch (error) {
const problem = toProblem(error);
if (problem.code === 'user_name_taken') {
this.serverErrors.set({ userName: problemMessage(error) });
} else if (problem.code === 'email_taken') {
this.serverErrors.set({ email: problemMessage(error) });
} else if (Object.keys(problem.errors).length) {
const fields: Partial<Record<Field, string>> = {};
for (const name of ['displayName', 'userName', 'email', 'password'] as Field[]) {
fields[name] = fieldErrors(error, name)[0];
}
this.serverErrors.set(fields);
} else {
this.error.set(problemMessage(error));
}
} finally {
this.busy.set(false);
}
}
}USER_NAME_PATTERNandPASSWORD_PATTERNare exported: the settings page of topic 21 checks a new password with the same rule.message(name)returns the one message to show under a field: first a server error for that field, then the first failing validator in a sensible order.@if (message('userName'); as m)stores the result in a template variable, so it is computed once per render. Notee['required']:noPropertyAccessFromIndexSignature(topic 15) wants the bracket notation for dictionary keys.serverErrorsmaps field names to the server's messages. The constructor subscribes to each control'svalueChanges, an Observable of its values, and clears the field's server error as soon as the user edits it.submit()sorts the server's answer.user_name_takenandemail_takenbelong to one field each (the friendly text fromproblemMessage); other validation errors are distributed by field withfieldErrors; anything else becomes the general error above the form.maxlengthon the inputs stops typing at the limit, so themaxLengthvalidators fire only for pasted text.@in the template is the@character. A bare@starts a control flow block in an Angular template, so a literal one must be written as an HTML entity.
Check
npm run build succeeds; the pages become reachable when the routes exist (next chapter).