Skip to content

Gentleman-Programming/Angular-20-Guide

Repository files navigation

Angular 20 Best Practices Demo Application

A comprehensive demonstration of modern Angular 20+ development patterns, best practices, and architectural decisions. This application showcases the latest Angular features including signals, zoneless change detection, standalone components, and modern development tooling.

๐Ÿš€ Features Demonstrated

Core Angular 20+ Features

  • Zoneless Change Detection (promoted to developer preview in v20)
  • Incremental Hydration (stable in v20)
  • Signal APIs (effect, linkedSignal, toSignal now stable)
  • Enhanced Template Expressions (exponential operator **, in operator, template literals)
  • Host Binding Type Checking (enabled with typeCheckHostBindings)
  • Style Guide Updates (no suffixes by default)
  • Experimental Vitest Support (official Angular v20 feature)
  • Control Flow Syntax (@if, @for, @switch, @empty)
  • Functional Providers and dependency injection
  • Resource API patterns for async operations
  • Modern HTTP Client with functional interceptors

Architecture Patterns

  • Atomic Design Principles (atoms, molecules, organisms)
  • Feature-based Folder Structure with barrel exports
  • Signal-first State Management with minimal RxJS
  • Container/Presentational Component patterns
  • Functional Guards and route protection
  • Modern Form Handling with reactive forms and signals

Development Best Practices

  • TypeScript 5.0+ with strict configuration
  • ESLint 9+ with Angular-specific rules
  • Prettier for consistent code formatting
  • Vitest for fast, modern testing
  • Path Aliases for clean imports
  • Performance Budgets and optimization

๐Ÿ“‹ Table of Contents

๐Ÿƒโ€โ™‚๏ธ Quick Start

Prerequisites

  • Node.js 18.19.0 or higher
  • npm 9.0.0 or higher

Installation

# Clone the repository
git clone <repository-url>
cd angular-20-best-practices

# Install dependencies
npm install

# Start development server
npm start

Available Scripts

npm start          # Start development server
npm run build      # Build for production
npm test           # Run tests with Vitest
npm run test:ui    # Run tests with UI
npm run test:coverage  # Generate test coverage
npm run lint       # Lint the codebase
npm run format     # Format code with Prettier
npm run typecheck  # Type check without emitting files

๐Ÿ“ Project Structure

src/
โ”œโ”€โ”€ shared/                 # Reusable components and services
โ”‚   โ”œโ”€โ”€ ui/                # Atomic design components
โ”‚   โ”‚   โ”œโ”€โ”€ button.ts      # Atom: Base button component
โ”‚   โ”‚   โ”œโ”€โ”€ input.ts       # Atom: Input field component
โ”‚   โ”‚   โ”œโ”€โ”€ field.ts       # Molecule: Input + label + validation
โ”‚   โ”‚   โ”œโ”€โ”€ modal.ts       # Molecule: Modal dialog
โ”‚   โ”‚   โ””โ”€โ”€ index.ts       # Barrel export
โ”‚   โ”œโ”€โ”€ data/              # Global services and state
โ”‚   โ”‚   โ”œโ”€โ”€ auth.ts        # Authentication service
โ”‚   โ”‚   โ”œโ”€โ”€ loading.ts     # Loading state management
โ”‚   โ”‚   โ””โ”€โ”€ index.ts       # Barrel export
โ”‚   โ””โ”€โ”€ utils/             # Utility functions
โ”œโ”€โ”€ features/              # Feature modules
โ”‚   โ”œโ”€โ”€ auth/              # Authentication feature
โ”‚   โ”‚   โ””โ”€โ”€ login.ts       # Login component
โ”‚   โ”œโ”€โ”€ dashboard/         # Dashboard feature
โ”‚   โ”‚   โ””โ”€โ”€ dashboard.ts   # Dashboard component
โ”‚   โ”œโ”€โ”€ user-management/   # User CRUD operations
โ”‚   โ”‚   โ”œโ”€โ”€ user-list.ts   # User list component
โ”‚   โ”‚   โ”œโ”€โ”€ user-form.ts   # User creation/editing
โ”‚   โ”‚   โ””โ”€โ”€ data/          # User-specific services
โ”‚   โ””โ”€โ”€ profile/           # User profile management
โ””โ”€โ”€ core/                  # Core application modules
    โ”œโ”€โ”€ layout/            # Layout components
    โ”‚   โ”œโ”€โ”€ header.ts      # Application header
    โ”‚   โ””โ”€โ”€ footer.ts      # Application footer
    โ””โ”€โ”€ guards/            # Route guards
        โ””โ”€โ”€ auth-guard.ts  # Authentication guard

๐Ÿ”ง Key Components

Atomic Design Implementation

Atoms (Basic UI Elements)

  • Button: Accessible button with variants and signal-based API
  • Input: Form input with ControlValueAccessor integration
  • Spinner: Loading indicator with size and color options

Molecules (Component Combinations)

  • Field: Input + label + validation messaging
  • Modal: Dialog with keyboard navigation and backdrop
  • LoadingIndicator: Global loading state display

Organisms (Complex Components)

  • UserList: Data table with filtering and actions
  • Dashboard: Statistics and activity overview
  • Header: Navigation with authentication state

Signal-Based Architecture

// Example: Signal-based service
@Injectable({ providedIn: 'root' })
export class UserService {
  private users = signal<User[]>([]);
  private filters = signal<UserFilters>({ search: '', role: 'all' });

  // Computed signal for derived state
  filteredUsers = computed(() => {
    const users = this.users();
    const { search, role } = this.filters();

    return users.filter(user => {
      const matchesSearch = !search || user.name.includes(search);
      const matchesRole = role === 'all' || user.role === role;
      return matchesSearch && matchesRole;
    });
  });
}

Modern Component Patterns

// Example: Modern component with signals
@Component({
  selector: 'app-example',
  template: `
    @if (isLoading()) {
      <app-spinner />
    } @else {
      @for (item of items(); track item.id) {
        <div>{{ item.name }}</div>
      } @empty {
        <p>No items found</p>
      }
    }
  `,
  host: {
    '[class.loading]': 'isLoading()',
    '(click)': 'handleClick($event)',
  },
})
export class ExampleComponent {
  items = input.required<Item[]>();
  isLoading = input(false);

  itemSelected = output<Item>();

  handleClick(event: Event) {
    // Handle click
  }
}

๐Ÿงช Testing Strategy

Framework: Vitest (Official Angular v20 Support)

The application uses Vitest as the primary testing framework, following the official Angular v20 recommendation:

# Install Vitest dependencies (already included)
npm i vitest jsdom --save-dev

# Run tests with Vitest
npm test

# Run tests with UI
npm run test:ui

# Generate coverage
npm run test:coverage

Testing Configuration

The project uses the new Angular v20 testing setup:

// angular.json
"test": {
  "builder": "@angular/build:unit-test",
  "options": {
    "tsConfig": "tsconfig.spec.json",
    "buildTarget": "angular-20-best-practices:build:development",
    "runner": "vitest"
  }
}

Testing Best Practices

  • Unit tests for components, services, and pipes
  • Signal-based testing for reactive state
  • Accessibility testing with proper ARIA attributes
  • Component harnesses for complex UI interactions
  • MSW (Mock Service Worker) for API mocking

๐Ÿ“ Development Guidelines

Code Style

  • Follow Airbnb JavaScript Style Guide adapted for Angular/TypeScript
  • Use descriptive and meaningful names for better readability
  • Keep components under 300 lines - split if exceeded
  • Prefer pure components and pure functions
  • Document purpose and usage with JSDoc comments

Component Guidelines

  • Use signal-based inputs/outputs exclusively
  • Implement host object for better performance
  • Follow atomic design principles for reusability
  • Apply accessibility patterns by default
  • Use modern template syntax with control flow

Service Guidelines

  • Use signals for state management over RxJS observables
  • Apply functional providers instead of NgModules
  • Implement proper error handling with user feedback
  • Follow single responsibility principle
  • Use dependency injection with inject() function

โšก Performance Considerations

Optimization Features

  • Zoneless change detection enabled by default
  • OnPush strategy not needed with zoneless
  • Lazy loading with dynamic imports
  • Bundle analysis and performance budgets
  • Image optimization with NgOptimizedImage

Performance Best Practices

// Example: Optimized component
@Component({
  // Zoneless - no need for OnPush
  template: `
    @defer (when shouldLoad()) {
      <heavy-component />
    } @placeholder {
      <app-spinner />
    }
  `,
})
export class OptimizedComponent {
  shouldLoad = signal(false);

  // Computed signals are automatically memoized
  expensiveComputation = computed(() => {
    return this.data().map(item => complexTransform(item));
  });
}

โ™ฟ Accessibility Features

Built-in Accessibility

  • Semantic HTML structure throughout
  • ARIA attributes for screen readers
  • Keyboard navigation support
  • Focus management in modals and forms
  • Color contrast compliance
  • Screen reader testing integration

Accessibility Patterns

// Example: Accessible component
@Component({
  template: `
    <button
      [attr.aria-label]="ariaLabel()"
      [attr.aria-expanded]="isExpanded()"
      [attr.aria-controls]="controlsId()"
      role="button"
      tabindex="0"
    >
      <ng-content />
    </button>
  `,
  host: {
    '(keydown.enter)': 'handleActivation()',
    '(keydown.space)': 'handleActivation()',
  },
})
export class AccessibleButton {
  ariaLabel = input<string>();
  isExpanded = input(false);
  controlsId = input<string>();
}

๐Ÿ”ฎ Future-Proofing

Preparing for Angular Evolution

  • Web Standards API usage where possible
  • Progressive enhancement strategies
  • Modern JavaScript features (ES2023+)
  • Framework interoperability considerations
  • Migration-friendly patterns

Experimental Features

  • Zoneless change detection (production-ready)
  • Resource API for data fetching
  • Functional component authoring (future)
  • Web Components integration

๐Ÿ“š Learning Resources

Official Documentation

Best Practices

  • This application demonstrates all patterns from the Angular 20+ style guide
  • Each component includes JSDoc comments explaining the patterns used
  • Check individual files for specific implementation details

๐Ÿค Contributing

  1. Follow the established code style and patterns
  2. Write tests for new features
  3. Update documentation as needed
  4. Run linting and formatting before committing
  5. Use conventional commit messages

๐Ÿ“„ License

This project is for educational purposes and demonstrates Angular 20+ best practices. Feel free to use these patterns in your own projects.


Built with Angular 20+ ๐Ÿš€

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published