Image for post: Angular 15 new features - complete guide

Angular 15 new features - complete guide

Angular 15, the latest major release from the Angular team, brings a host of new features and improvements aimed at enhancing developer productivity and application performance. Here's an in-depth overview of the most notable features and updates introduced.

Standalone APIs, components, directives, and pipes

The standalone APIs in Angular 15 are now stable, which means you can use components, directives, and pipes without NgModule. This represents a significant shift in how Angular applications are structured, making code more modular and easier to manage.

Benefits

  • Simplified module structure
  • Easier file organization without updating multiple NgModule declarations
  • Reduced boilerplate code
  • Better tree-shaking for smaller bundle sizes

Example: Standalone Component

import { Component } from '@angular/core';import { CommonModule } from '@angular/common';@Component({ selector: 'hello', template: `<h1>Hello World</h1>`, standalone: true, imports: [CommonModule] // Import dependencies directly})export class HelloComponent {}

Example: Standalone Directive

import { Directive, ElementRef, HostListener } from '@angular/core';@Directive({ selector: '[appHighlight]', standalone: true})export class HighlightDirective { constructor(private el: ElementRef) {} @HostListener('mouseenter') onMouseEnter() { this.el.nativeElement.style.backgroundColor = 'yellow'; } @HostListener('mouseleave') onMouseLeave() { this.el.nativeElement.style.backgroundColor = ''; }}

Example: Standalone Pipe

import { Pipe, PipeTransform } from '@angular/core';@Pipe({ name: 'exponential', standalone: true})export class ExponentialPipe implements PipeTransform { transform(value: number, exponent = 1): number { return Math.pow(value, exponent); }}

Bootstrapping a Standalone Application

import { bootstrapApplication } from '@angular/platform-browser';import { AppComponent } from './app/app.component';bootstrapApplication(AppComponent, { providers: [ // Add your providers here ]});

Directive composition API

The Directive composition API allows you to create Angular directives that can be composed with other directives, combining multiple directives on a single host element. This makes directives more powerful and reusable.

Example:

import { Component, Directive } from '@angular/core';// Base directives@Directive({ selector: '[tooltip]', standalone: true})export class TooltipDirective { // Tooltip logic}@Directive({ selector: '[menu]', standalone: true})export class MenuDirective { // Menu logic}// Component that uses composed directives@Component({ selector: 'app-button', template: `<button>Click me</button>`, standalone: true, hostDirectives: [ TooltipDirective, { directive: MenuDirective, inputs: ['menuItems'] } ]})export class ButtonComponent {}

Image directives (NgOptimizedImage)

The new NgOptimizedImage directive is designed to dramatically improve image loading performance in Angular applications with automatic optimizations.

Features

  • Automatic lazy loading
  • Responsive images with automatic srcset generation
  • Priority loading for LCP images
  • WebP format optimization
  • Built-in warnings for missing attributes

Example: basic usage

import { Component } from '@angular/core';import { NgOptimizedImage } from '@angular/common';@Component({ selector: 'app-gallery', standalone: true, imports: [NgOptimizedImage], template: ` <img ngSrc="hero-image.jpg" width="400" height="300" priority alt="Hero image"> <img ngSrc="thumbnail.jpg" width="200" height="150" alt="Thumbnail"> `})export class GalleryComponent {}

Example: with Loader Configuration

import { ApplicationConfig } from '@angular/core';import { provideImgixLoader } from '@angular/common';export const appConfig: ApplicationConfig = { providers: [ provideImgixLoader('https://my-domain.imgix.net/') ]};

Improved server-side rendering (SSR) with Angular Universal

Angular 15 enhances server-side rendering (SSR) capabilities with better streaming support and improved performance, enabling faster Time-to-First-Byte (TTFB) and more efficient hydration.

Benefits

  • Faster initial page loads
  • Improved SEO
  • Better Core Web Vitals scores
  • Reduced complexity in SSR setup

Example of a basic SSR setup

// server.tsimport 'zone.js/node';import { APP_BASE_HREF } from '@angular/common';import { CommonEngine } from '@angular/ssr';import express from 'express';import { fileURLToPath } from 'node:url';import { dirname, join, resolve } from 'node:path';import bootstrap from './src/main.server';const app = express();const serverDistFolder = dirname(fileURLToPath(import.meta.url));const browserDistFolder = resolve(serverDistFolder, '../browser');app.get('*', (req, res, next) => { const { protocol, originalUrl, baseUrl, headers } = req; commonEngine .render({ bootstrap, documentFilePath: join(browserDistFolder, 'index.html'), url: `${protocol}://${headers.host}${originalUrl}`, publicPath: browserDistFolder, providers: [{ provide: APP_BASE_HREF, useValue: baseUrl }], }) .then((html) => res.send(html)) .catch((err) => next(err));});

Enhanced TypeScript support

Angular 15 introduced enhanced TypeScript support with TypeScript 4.8+ compatibility, providing better developer tooling and more robust applications.

Improvements

  • More precise type-checking
  • Stricter types for better error detection
  • Better IDE support and IntelliSense
  • Improved template type-checking

Example: strict template checking

import { Component } from '@angular/core';interface User { name: string; age: number;}@Component({ selector: 'app-user', standalone: true, template: ` <div> <p>{{ user.name }}</p> <p>{{ user.age }}</p> <!-- TypeScript will catch errors like {{ user.invalid }} --> </div> `})export class UserComponent { user: User = { name: 'John', age: 30 };}

CDK and Angular Material updates

The Component Dev Kit (CDK) and Angular Material received several updates, including new components, enhanced accessibility features, and improved documentation.

New features

  • Improved accessibility (ARIA support)
  • New components and design patterns
  • Better documentation with examples
  • Enhanced theming capabilities

Example: using CDK dialog

import { Component } from '@angular/core';import { Dialog } from '@angular/cdk/dialog';@Component({ selector: 'app-root', standalone: true, template: `<button (click)="openDialog()">Open Dialog</button>`})export class AppComponent { constructor(private dialog: Dialog) {} openDialog() { this.dialog.open(DialogComponent, { width: '400px', data: { message: 'Hello from dialog!' } }); }}

Enhanced testing, debugging tools, and stack traces

Angular 15 introduces significant improvements to testing and debugging capabilities.

Improvements

  • Cleaner stack traces
  • Better error messages
  • Improved debugging information
  • Enhanced TestBed configuration

Example: Testing Standalone Components

import { ComponentFixture, TestBed } from '@angular/core/testing';import { HelloComponent } from './hello.component';describe('HelloComponent', () => { let component: HelloComponent; let fixture: ComponentFixture<HelloComponent>; beforeEach(async () => { await TestBed.configureTestingModule({ imports: [HelloComponent] // Import standalone component directly }).compileComponents(); fixture = TestBed.createComponent(HelloComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should display hello world', () => { const compiled = fixture.nativeElement; expect(compiled.querySelector('h1').textContent).toContain('Hello World'); });});

Smaller bundle sizes and performance optimizations

Performance optimizations in Angular 15 help reduce bundle sizes and enhance application performance.

Optimizations Include

  • Tree-shaking improvements with standalone APIs
  • Reduced runtime overhead
  • Better code splitting
  • Optimized change detection

Tips for Further Optimization

// Use lazy loading for routesconst routes: Routes = [ { path: 'admin', loadComponent: () => import('./admin/admin.component').then(m => m.AdminComponent) }];// Use OnPush change detection strategy@Component({ selector: 'app-optimized', standalone: true, changeDetection: ChangeDetectionStrategy.OnPush, template: `...`})export class OptimizedComponent {}

Experimental ESBuild Support

Angular 15 includes experimental support for ESBuild, a significantly faster JavaScript bundler.

Benefits

  • Faster build times (up to 10x faster)
  • Support for file replacement
  • SVG template support
  • Sass compilation
  • Watch mode support

Usage

// angular.json{ "projects": { "your-app": { "architect": { "build": { "builder": "@angular-devkit/build-angular:browser-esbuild", "options": { // your options } } } } }}

Router Standalone API

The standalone router API allows using routing without NgModule, making it easier to build single-page applications.

Example of a standalone router configuration:

import { bootstrapApplication } from '@angular/platform-browser';import { provideRouter } from '@angular/router';import { AppComponent } from './app/app.component';const routes = [ { path: '', loadComponent: () => import('./home/home.component').then(m => m.HomeComponent) }, { path: 'about', loadComponent: () => import('./about/about.component').then(m => m.AboutComponent) }, { path: '**', redirectTo: '' }];bootstrapApplication(AppComponent, { providers: [ provideRouter(routes) ]});

Example of a router configuration with features:

import { bootstrapApplication } from '@angular/platform-browser';import { provideRouter, withDebugTracing, withHashLocation } from '@angular/router';import { AppComponent } from './app/app.component';import { routes } from './app/app.routes';bootstrapApplication(AppComponent, { providers: [ provideRouter( routes, withDebugTracing(), // Enable debug tracing withHashLocation() // Use hash location strategy ) ]});

Developer experience improvements

Angular 15 brings numerous changes to improve the overall developer experience:

  • Better CLI commands: More intuitive and helpful command-line interface
  • Improved documentation: Enhanced guides and API documentation
  • Modern development workflows: Better support for contemporary tools and practices
  • Auto-completion improvements: Enhanced IDE support

Deprecations and removals

As with any major release, Angular 15 deprecates certain features:

  • Legacy NgModules approach (not removed, but standalone is recommended)
  • Certain older APIs and patterns
  • Review the official deprecation guide for complete details

Migration Tips

# Update your Angular CLInpm install -g @angular/cli@15# Update your projectng update @angular/core@15 @angular/cli@15# Check for deprecationsng update

Upgrading to Angular 15

The official Angular website offers a comprehensive update guide with step-by-step instructions.

Upgrade steps

  1. Check compatibility: Ensure your dependencies support Angular 15
  2. Update Angular CLI: npm install -g @angular/cli@15
  3. Run update command: ng update @angular/core@15 @angular/cli@15
  4. Update dependencies: Update third-party libraries
  5. Test thoroughly: Run your test suite
  6. Review deprecations: Check for deprecated APIs in your code

Best practices

  • Wait a few months after release before upgrading production applications
  • Test in a staging environment first
  • Review breaking changes in the changelog
  • Update dependencies incrementally

Nx.dev and Angular Versions

If you're using the Nx.dev workspace for your project, ensure version compatibility:

  • Choose the Nx version that corresponds to your Angular version
  • Creating a new project with the latest Nx will include the latest Angular version
  • Nx is working on supporting flexible Angular version selection

Example: Creating a New Nx Workspace

npx create-nx-workspace@latest my-workspace# Select Angular as the preset# Nx will automatically use a compatible Angular version

Conclusion

Angular 15 represents a significant step forward in the framework's evolution, with standalone APIs being the headline feature. The focus on developer experience, performance, and modern development practices makes Angular more accessible and powerful than ever.

Key Takeaways

  • Standalone APIs simplify application architecture
  • NgOptimizedImage dramatically improves image performance
  • Enhanced SSR provides better performance and user experience
  • ESBuild support speeds up development builds
  • Improved TypeScript support catches errors earlier

Whether you're starting a new project or upgrading an existing one, Angular 15 offers compelling reasons to adopt its new features and best practices.

Resources:

Resources