Angular Tutorial – Part 3
Angular Tutorial – Part 3: Advanced App Development
Go further with dynamic forms, reusable components, signal and RxJS interop, server rendering, internationalization and scalable project structure.
1Dynamic Reactive Forms
Use a FormArray when the user can add or remove a variable number of controls. Keep validation in the form model so it can be tested and reused.
import { Component, inject } from '@angular/core';
import { FormArray, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'app-team-form',
standalone: true,
template: `
<form [formGroup]="form" (ngSubmit)="save()">
<div formArrayName="emails">
@for (control of emails.controls; track $index; let i = $index) {
<label [for]="'email-' + i">Email {{ i + 1 }}</label>
<input [id]="'email-' + i" [formControlName]="i" type="email">
<button type="button" (click)="removeEmail(i)">Remove</button>
}
</div>
<button type="button" (click)="addEmail()">Add email</button>
<button type="submit" [disabled]="form.invalid">Save</button>
</form>
`
})
export class TeamFormComponent {
private fb = inject(FormBuilder);
form = this.fb.group({
emails: this.fb.array([this.fb.control('', {
validators: [Validators.required, Validators.email]
})])
});
get emails() { return this.form.controls.emails; }
addEmail() {
this.emails.push(this.fb.control('', {
validators: [Validators.required, Validators.email]
}));
}
removeEmail(index: number) {
if (this.emails.length > 1) this.emails.removeAt(index);
}
save() {
if (this.form.valid) console.log(this.form.getRawValue());
}
}2Reusable Components and Content Projection
Content projection lets a reusable component provide layout and behavior while callers supply the content. Use a named slot when a component has distinct content areas.
<article class="card">
<header>
<ng-content select="[card-title]" />
</header>
<div class="card-body">
<ng-content />
</div>
<footer>
<ng-content select="[card-actions]" />
</footer>
</article><app-card>
<h2 card-title>Profile</h2>
<p>Update your contact details.</p>
<button card-actions type="button">Edit profile</button>
</app-card>Keep reusable components focused: expose clear inputs and outputs, and avoid coupling them directly to a specific page or API.
3Build a Custom Form Control
Implement ControlValueAccessor when a custom UI should work with formControlName. The Angular forms API calls these methods to keep the view and form model synchronized.
import { Component, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({
selector: 'app-rating',
standalone: true,
template: `
<label>
Rating
<input type="range" min="0" max="5"
[value]="value" [disabled]="disabled"
(input)="update($event)" (blur)="markTouched()">
</label>
<span>{{ value }} / 5</span>
`,
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => RatingComponent),
multi: true
}]
})
export class RatingComponent implements ControlValueAccessor {
value = 0;
disabled = false;
private onChange = (value: number) => {};
private onTouched = () => {};
writeValue(value: number | null) { this.value = value ?? 0; }
registerOnChange(fn: (value: number) => void) { this.onChange = fn; }
registerOnTouched(fn: () => void) { this.onTouched = fn; }
setDisabledState(disabled: boolean) { this.disabled = disabled; }
update(event: Event) {
this.value = Number((event.target as HTMLInputElement).value);
this.onChange(this.value);
}
markTouched() { this.onTouched(); }
}4Connect Signals and RxJS
Use toSignal to read an Observable as a signal in a component. Provide an initial value when the UI should have a useful state before the first result arrives.
import { Component, inject } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { HttpClient } from '@angular/common/http';
import { catchError, of } from 'rxjs';
interface Product {
id: number;
name: string;
}
@Component({
selector: 'app-products',
standalone: true,
template: `
<ul>
@for (product of products(); track product.id) {
<li>{{ product.name }}</li>
}
</ul>
`
})
export class ProductsComponent {
private http = inject(HttpClient);
products = toSignal(
this.http.get<Product[]>('/api/products').pipe(
catchError(() => of([]))
),
{ initialValue: [] }
);
}Choose one clear source of truth for each piece of state. Convert between signals and Observables at integration boundaries rather than repeatedly switching representations.
5Server Rendering and Hydration
Server-side rendering (SSR) sends rendered HTML from the server. Hydration lets Angular take over that HTML in the browser, which can improve the first display and support content discovery.
- Add SSR to an existing Angular application with the Angular CLI:
ng add @angular/ssr. - Build and run the server-rendered app using the scripts generated for your project.
- Keep browser-only APIs such as
windowandlocalStorageout of server-only execution paths. - Ensure server and browser render compatible markup so hydration can reuse the page correctly.
6Internationalization
Design for translation early. Keep user-facing text out of business logic, allow translated labels to be longer, and format dates and numbers using locale-aware tools.
<h1 i18n="@@welcomeTitle">Welcome to the dashboard</h1>
<button i18n="@@saveButton">Save changes</button>const amount = new Intl.NumberFormat(locale, {
style: 'currency',
currency: 'USD'
}).format(total);Angular's extraction and build tools can prepare marked messages for translation. Verify each supported locale, including right-to-left layouts when applicable.
7Organize a Growing Application
Group code around product features so each area can evolve independently. A small app does not need every possible abstraction; add boundaries when they make responsibilities clearer.
src/app/
core/
auth/
http/
shared/
ui/
pipes/
features/
products/
data-access/
pages/
ui/
products.routes.ts
orders/
data-access/
pages/
ui/
orders.routes.ts
app.routes.ts- Keep feature-specific components and data access close together.
- Use shared UI components for genuinely reusable presentation.
- Lazy-load large feature areas at route boundaries.
- Keep API models and server validation distinct from assumptions made by the UI.
8Capstone Project Checklist
Build a small product catalog to practice the concepts from Parts 1–3:
- Create a product list and details page with lazy-loaded routes.
- Load data through a service and show loading, empty and error states.
- Add a reactive form with validation for creating or editing a product.
- Use a shared signal store for a cart and display its item count.
- Write tests for a component, a service and a form validation rule.
- Check keyboard access, mobile layout and production build output.
🎉 You have completed Angular Tutorial Part 3. Keep experimenting, testing and learning from real projects. — A143MK
No comments :
Post a Comment
Please Write a Message for Programming or something else 🙏