Powered by Blogger.

Angular Tutorial – Part 3

No comments :

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.

✍️ By A143MK  •  📘 Angular Tutorial – Part 3

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.

typescript
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());
  }
}
💡 For accessible forms, connect each label to its input and show clear validation text when a field is invalid and has been touched.

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.

card component template
<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>
usage
<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.

typescript
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.

typescript
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.

  1. Add SSR to an existing Angular application with the Angular CLI: ng add @angular/ssr.
  2. Build and run the server-rendered app using the scripts generated for your project.
  3. Keep browser-only APIs such as window and localStorage out of server-only execution paths.
  4. Ensure server and browser render compatible markup so hydration can reuse the page correctly.
ℹ️ SSR deployment needs a Node-capable or SSR-compatible host. A static-only host cannot execute the server renderer.

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.

template
<h1 i18n="@@welcomeTitle">Welcome to the dashboard</h1>
<button i18n="@@saveButton">Save changes</button>
typescript
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.

example structure
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:

  1. Create a product list and details page with lazy-loaded routes.
  2. Load data through a service and show loading, empty and error states.
  3. Add a reactive form with validation for creating or editing a product.
  4. Use a shared signal store for a cart and display its item count.
  5. Write tests for a component, a service and a form validation rule.
  6. Check keyboard access, mobile layout and production build output.
✅ You now have a path from Angular fundamentals to a structured, testable application. Build one feature at a time and keep the user experience accessible.

🎉 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 🙏