Andrei Pall

Linux Software Engineering

Angular CRUD application using Signals

In this tutorial, we will create a complete Angular CRUD application using Signals, standalone components, Reactive Forms and TypeScript.

We will build a product management application that supports:

  • Create – Add a new product.
  • Read – Display all products.
  • Update – Edit an existing product.
  • Delete – Remove a product.
  • Search products using computed signals.
  • Form validation.
  • Automatic UI updates using Signals.
  • Persistent storage using localStorage.

We will use Bootstrap 5 for styling and modern Angular syntax, including @if, @for, signal(), computed() and inject().

The initial implementation will not require a backend, but the service architecture can be adapted to a Spring Boot REST API.

1. Application preview

iframe

2. Create the Angular project

Install Angular CLI if you do not already have it:

npm install -g @angular/cli

Create the project:

ng new angular-signals-crud --routing --style=css --standalone --ssr=false

Navigate to the project and install Bootstrap:

cd angular-signals-crud

npm install bootstrap bootstrap-icons

Add the following to src/styles.css:

@import 'bootstrap/dist/css/bootstrap.min.css';
@import 'bootstrap-icons/font/bootstrap-icons.css';

body {
    background-color: #f5f6fa;
}

3. Project directory structure

We will use a feature-based directory structure, which is suitable for modern standalone Angular applications.

src/app/

features/

products/

models/

product.model.ts

services/

product.service.ts

components/

product-list/

product-list.component.ts

product-list.component.html

product-form/

product-form.component.ts

product-form.component.html

app.routes.ts

app.config.ts

app.ts

app.html

4. Understanding the application architecture

The ProductService acts as a centralized reactive state store. Whenever a component modifies the products signal, Angular automatically updates the components that depend on it.

There is no need for a BehaviorSubject, manual subscriptions or NgRx for this simple application.

5. Create the product model

src/app/features/products/models/product.model.ts

export interface Product {
    id: number;
    name: string;
    price: number;
    quantity: number;
}

export type ProductInput = Omit<Product, 'id'>;

The ProductInput type contains all product properties except id. We use it when creating or updating products because the ID is managed separately.

6. Create the service using Signals

This is the most important part of the application.

src/app/features/products/services/product.service.ts

import { Injectable, signal, computed } from '@angular/core';
import { Product, ProductInput } from '../models/product.model';

@Injectable({
    providedIn: 'root'
})
export class ProductService {

    private readonly storageKey = 'products';

    private readonly productsSignal = signal<Product[]>(
        this.loadProducts()
    );

    readonly products = this.productsSignal.asReadonly();

    readonly totalProducts = computed(() =>
        this.products().length
    );

    readonly totalQuantity = computed(() =>
        this.products().reduce(
            (total, product) => total + product.quantity,
            0
        )
    );

    readonly totalValue = computed(() =>
        this.products().reduce(
            (total, product) =>
                total + product.price * product.quantity,
            0
        )
    );

    // READ
    getById(id: number): Product | undefined {
        return this.products().find(product => product.id === id);
    }

    // CREATE
    create(product: ProductInput): void {

        const id = Math.max(
            0,
            ...this.products().map(p => p.id)
        ) + 1;

        const newProduct: Product = {
            ...product,
            id
        };

        this.productsSignal.update(products => [
            ...products,
            newProduct
        ]);

        this.saveProducts();
    }

    // UPDATE
    update(id: number, product: ProductInput): void {

        this.productsSignal.update(products =>
            products.map(p =>
                p.id === id
                    ? { ...p, ...product }
                    : p
            )
        );

        this.saveProducts();
    }

    // DELETE
    delete(id: number): void {

        this.productsSignal.update(products =>
            products.filter(product => product.id !== id)
        );

        this.saveProducts();
    }

    private saveProducts(): void {

        localStorage.setItem(
            this.storageKey,
            JSON.stringify(this.products())
        );
    }

    private loadProducts(): Product[] {

        const data = localStorage.getItem(this.storageKey);

        if (data) {
            return JSON.parse(data);
        }

        return [
            {
                id: 1,
                name: 'Laptop',
                price: 1200,
                quantity: 5
            },
            {
                id: 2,
                name: 'Keyboard',
                price: 75,
                quantity: 12
            },
            {
                id: 3,
                name: 'Monitor',
                price: 300,
                quantity: 8
            }
        ];
    }
}

6.1. How signal() works

private readonly productsSignal = signal<Product[]>([]);

A signal is a reactive container that holds a value and notifies its consumers when that value changes.

To read its value, call it as a function:

const products = this.productsSignal();

To replace its value:

this.productsSignal.set([
    {
        id: 1,
        name: 'Laptop',
        price: 1200,
        quantity: 5
    }
]);

To modify its value based on the previous value:

this.productsSignal.update(products => [
    ...products,
    newProduct
]);

6.2. How asReadonly() works

readonly products = this.productsSignal.asReadonly();

This exposes the signal to components without exposing its set() and update() methods.

Components can read the signal:

this.productService.products();

But they cannot do this:

// Compilation error
this.productService.products.set([]);

All state modifications should go through the service’s CRUD methods.

Note that asReadonly() does not deeply freeze the underlying objects. You should still avoid directly mutating products.

6.3. How computed() works

readonly totalProducts = computed(() =>
    this.products().length
);

A computed signal derives its value from other signals.

Whenever the products signal changes, Angular invalidates the computed value and recalculates it when it is next read.

Writable signal — products

3 products

Delete Create

Automatic dependency tracking

computed()

3

Total products

Component template

3

Displayed rows

Click Create or Delete to simulate how a signal propagates changes to its consumers.

Computed signals are read-only, lazily evaluated and memoized. They are ideal for totals, filtering, sorting and other derived data.

7. Create the product list component

The product list component will display all products, provide search functionality and allow users to navigate to the create and edit pages or delete products.

7.1. TypeScript component

src/app/features/products/components/product-list/product-list.component.ts

import {
    Component,
    ChangeDetectionStrategy,
    inject,
    signal,
    computed
} from '@angular/core';

import { CurrencyPipe } from '@angular/common';
import { RouterLink } from '@angular/router';

import { ProductService } from '../../services/product.service';
import { Product } from '../../models/product.model';

@Component({
    selector: 'app-product-list',
    standalone: true,
    imports: [
        CurrencyPipe,
        RouterLink
    ],
    templateUrl: './product-list.component.html',
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class ProductListComponent {

    private readonly productService = inject(ProductService);

    readonly products = this.productService.products;

    readonly totalProducts = this.productService.totalProducts;
    readonly totalQuantity = this.productService.totalQuantity;
    readonly totalValue = this.productService.totalValue;

    readonly searchTerm = signal('');

    readonly filteredProducts = computed(() => {

        const search = this.searchTerm().trim().toLowerCase();

        return this.products().filter(product =>
            product.name.toLowerCase().includes(search)
        );
    });

    onSearch(event: Event): void {

        const input = event.target as HTMLInputElement;

        this.searchTerm.set(input.value);
    }

    deleteProduct(product: Product): void {

        if (confirm(`Are you sure you want to delete ${product.name}?`)) {
            this.productService.delete(product.id);
        }
    }
}

7.2. HTML template

src/app/features/products/components/product-list/product-list.component.html

<div class="container py-4">

    <div class="d-flex justify-content-between align-items-center mb-4">

        <h2>Product management</h2>

        <a routerLink="/products/create" class="btn btn-primary">
            <i class="bi bi-plus-lg"></i>
            Add product
        </a>

    </div>

    <!-- Statistics -->

    <div class="row g-3 mb-4">

        <div class="col-md-4">
            <div class="card shadow-sm">
                <div class="card-body">
                    <h6 class="text-muted">Total products</h6>
                    <h3></h3>
                </div>
            </div>
        </div>

        <div class="col-md-4">
            <div class="card shadow-sm">
                <div class="card-body">
                    <h6 class="text-muted">Total quantity</h6>
                    <h3></h3>
                </div>
            </div>
        </div>

        <div class="col-md-4">
            <div class="card shadow-sm">
                <div class="card-body">
                    <h6 class="text-muted">Inventory value</h6>
                    <h3></h3>
                </div>
            </div>
        </div>

    </div>

    <div class="card shadow-sm">

        <div class="card-body">

            <!-- Search -->

            <div class="mb-3">

                <label for="search" class="form-label">
                    Search products
                </label>

                <input
                    type="search"
                    id="search"
                    class="form-control"
                    placeholder="Enter product name..."
                    [value]="searchTerm()"
                    (input)="onSearch($event)"
                >

            </div>

            <!-- Product table -->

            <div class="table-responsive">

                <table class="table table-hover align-middle">

                    <thead>
                        <tr>
                            <th scope="col">ID</th>
                            <th scope="col">Name</th>
                            <th scope="col">Price</th>
                            <th scope="col">Quantity</th>
                            <th scope="col">Total</th>
                            <th scope="col">Actions</th>
                        </tr>
                    </thead>

                    <tbody>

                        @for (product of filteredProducts(); track product.id) {

                            <tr>

                                <td></td>

                                <td></td>

                                <td></td>

                                <td></td>

                                <td>
                                    
                                </td>

                                <td>

                                    <a
                                        [routerLink]="['/products/edit', product.id]"
                                        class="btn btn-sm btn-outline-primary me-2"
                                    >
                                        <i class="bi bi-pencil"></i>
                                        Edit
                                    </a>

                                    <button
                                        type="button"
                                        class="btn btn-sm btn-outline-danger"
                                        (click)="deleteProduct(product)"
                                    >
                                        <i class="bi bi-trash"></i>
                                        Delete
                                    </button>

                                </td>

                            </tr>

                        } @empty {

                            <tr>
                                <td colspan="6" class="text-center text-muted py-4">
                                    No products found.
                                </td>
                            </tr>

                        }

                    </tbody>

                </table>

            </div>

            <div class="text-muted">
                Showing 
                of  products
            </div>

        </div>

    </div>

</div>

7.3. Understanding reactive search with Signals

We have two signals involved in the search functionality:

readonly searchTerm = signal('');

readonly filteredProducts = computed(() => {

    const search = this.searchTerm().toLowerCase();

    return this.products().filter(product =>
        product.name.toLowerCase().includes(search)
    );
});

The computed signal depends on both searchTerm and products.

Product Price
Laptop $1,200
Keyboard $75
Monitor $300
Mouse $25
USB Cable $15

filteredProducts(): 5 of 5 products

Whenever either dependency changes, the filtered results are automatically updated.

This means that we do not need to manually call a filtering method after creating, updating or deleting a product.

7.4. Why use ChangeDetectionStrategy.OnPush?

changeDetection: ChangeDetectionStrategy.OnPush

When a signal is read inside an OnPush component’s template, Angular tracks it as a dependency of that component.

When the signal changes, Angular marks the component for checking.

This makes Signals and OnPush a good combination for efficient UI updates.

8. Create the product form component

We will reuse the same component for both creating and editing products.

The form will use Angular Reactive Forms for validation and Signals for the component’s state.

8.1. TypeScript component

src/app/features/products/components/product-form/product-form.component.ts

import {
    Component,
    ChangeDetectionStrategy,
    OnInit,
    inject,
    signal,
    computed
} from '@angular/core';

import {
    FormBuilder,
    ReactiveFormsModule,
    Validators
} from '@angular/forms';

import {
    ActivatedRoute,
    Router,
    RouterLink
} from '@angular/router';

import { ProductService } from '../../services/product.service';

@Component({
    selector: 'app-product-form',
    standalone: true,
    imports: [
        ReactiveFormsModule,
        RouterLink
    ],
    templateUrl: './product-form.component.html',
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class ProductFormComponent implements OnInit {

    private readonly fb = inject(FormBuilder);
    private readonly productService = inject(ProductService);
    private readonly route = inject(ActivatedRoute);
    private readonly router = inject(Router);

    readonly productId = signal<number | null>(null);

    readonly isEditMode = computed(() =>
        this.productId() !== null
    );

    readonly pageTitle = computed(() =>
        this.isEditMode() ? 'Edit product' : 'Create product'
    );

    readonly submitted = signal(false);

    readonly productForm = this.fb.nonNullable.group({

        name: [
            '',
            [
                Validators.required,
                Validators.minLength(2),
                Validators.maxLength(100),
                Validators.pattern(/\S/)
            ]
        ],

        price: [
            0,
            [
                Validators.required,
                Validators.min(0)
            ]
        ],

        quantity: [
            0,
            [
                Validators.required,
                Validators.min(0),
                Validators.pattern(/^\d+$/)
            ]
        ]

    });

    ngOnInit(): void {

        const id = this.route.snapshot.paramMap.get('id');

        if (id !== null) {

            const product = this.productService.getById(Number(id));

            if (!product) {
                this.router.navigate(['/products']);
                return;
            }

            this.productId.set(product.id);

            this.productForm.patchValue({
                name: product.name,
                price: product.price,
                quantity: product.quantity
            });
        }
    }

    onSubmit(): void {

        this.submitted.set(true);

        if (this.productForm.invalid) {
            this.productForm.markAllAsTouched();
            return;
        }

        const formValue = this.productForm.getRawValue();

        const product = {
            ...formValue,
            name: formValue.name.trim()
        };

        if (product.name.length < 2) {
            this.productForm.controls.name.setErrors({
                minlength: true
            });
            return;
        }

        const id = this.productId();

        if (id !== null) {

            this.productService.update(id, product);

        } else {

            this.productService.create(product);

        }

        this.router.navigate(['/products']);
    }
}

8.2. HTML template

src/app/features/products/components/product-form/product-form.component.html

<div class="container py-4">

    <div class="row justify-content-center">

        <div class="col-lg-6">

            <div class="card shadow-sm">

                <div class="card-header bg-white py-3">

                    <h4 class="mb-0"></h4>

                </div>

                <div class="card-body">

                    <form
                        [formGroup]="productForm"
                        (ngSubmit)="onSubmit()"
                    >

                        <!-- Product name -->

                        <div class="mb-3">

                            <label for="name" class="form-label">
                                Product name
                            </label>

                            <input
                                type="text"
                                id="name"
                                class="form-control"
                                formControlName="name"
                                [class.is-invalid]="
                                    submitted() &&
                                    productForm.controls.name.invalid
                                "
                            >

                            @if (submitted() && productForm.controls.name.invalid) {

                                <div class="invalid-feedback">

                                    @if (productForm.controls.name.hasError('required')) {
                                        Product name is required.
                                    }

                                    @if (productForm.controls.name.hasError('minlength')) {
                                        Product name must contain at least 2 characters.
                                    }

                                    @if (productForm.controls.name.hasError('maxlength')) {
                                        Product name cannot exceed 100 characters.
                                    }

                                    @if (productForm.controls.name.hasError('pattern')) {
                                        Product name cannot contain only whitespace.
                                    }

                                </div>

                            }

                        </div>

                        <!-- Price -->

                        <div class="mb-3">

                            <label for="price" class="form-label">
                                Price
                            </label>

                            <input
                                type="number"
                                id="price"
                                class="form-control"
                                formControlName="price"
                                min="0"
                                step="0.01"
                                [class.is-invalid]="
                                    submitted() &&
                                    productForm.controls.price.invalid
                                "
                            >

                            @if (submitted() && productForm.controls.price.invalid) {

                                <div class="invalid-feedback">
                                    Enter a valid non-negative price.
                                </div>

                            }

                        </div>

                        <!-- Quantity -->

                        <div class="mb-3">

                            <label for="quantity" class="form-label">
                                Quantity
                            </label>

                            <input
                                type="number"
                                id="quantity"
                                class="form-control"
                                formControlName="quantity"
                                min="0"
                                step="1"
                                [class.is-invalid]="
                                    submitted() &&
                                    productForm.controls.quantity.invalid
                                "
                            >

                            @if (submitted() && productForm.controls.quantity.invalid) {

                                <div class="invalid-feedback">
                                    Enter a valid non-negative integer.
                                </div>

                            }

                        </div>

                        <!-- Buttons -->

                        <div class="d-flex gap-2">

                            <button type="submit" class="btn btn-primary">

                                @if (isEditMode()) {
                                    Update product
                                } @else {
                                    Create product
                                }

                            </button>

                            <a routerLink="/products" class="btn btn-secondary">
                                Cancel
                            </a>

                        </div>

                    </form>

                </div>

            </div>

        </div>

    </div>

</div>

8.3. Understanding the form signals

We use a writable signal to store the ID of the product being edited:

readonly productId = signal<number | null>(null);

We then derive two computed signals from it:

readonly isEditMode = computed(() =>
    this.productId() !== null
);

readonly pageTitle = computed(() =>
    this.isEditMode() ? 'Edit product' : 'Create product'
);

This creates a chain of reactive dependencies.

Create modeEdit mode

productId()

null

isEditMode()

false

pageTitle()

Create product

Create product

Product name

Enter product name

Price

0

Quantity

0

Create product

Cancel

Switch between the two modes to see how the derived signal values and template change.

We don’t need to manually update the page title or button text when the product ID changes.

9. Configure Angular routing

src/app/app.routes.ts

import { Routes } from '@angular/router';

export const routes: Routes = [

    {
        path: '',
        redirectTo: 'products',
        pathMatch: 'full'
    },

    {
        path: 'products',
        loadComponent: () =>
            import(
                './features/products/components/product-list/product-list.component'
            ).then(m => m.ProductListComponent)
    },

    {
        path: 'products/create',
        loadComponent: () =>
            import(
                './features/products/components/product-form/product-form.component'
            ).then(m => m.ProductFormComponent)
    },

    {
        path: 'products/edit/:id',
        loadComponent: () =>
            import(
                './features/products/components/product-form/product-form.component'
            ).then(m => m.ProductFormComponent)
    },

    {
        path: '**',
        redirectTo: 'products'
    }

];

The application has the following routes:

URL Component Purpose
/ Redirect Redirect to products
/products ProductListComponent List products
/products/create ProductFormComponent Create product
/products/edit/1 ProductFormComponent Edit product with ID 1
** Redirect Handle unknown URLs

We use loadComponent() instead of component to enable lazy loading of standalone components.

10. Configure the application

src/app/app.config.ts

import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';

import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
    providers: [
        provideRouter(routes)
    ]
};

No AppModule is necessary because the application uses standalone components.

11. Create the root component

src/app/app.ts

import { Component } from '@angular/core';

import {
    RouterOutlet,
    RouterLink
} from '@angular/router';

@Component({
    selector: 'app-root',
    standalone: true,
    imports: [
        RouterOutlet,
        RouterLink
    ],
    templateUrl: './app.html'
})
export class App {
}

src/app/app.html

<nav class="navbar navbar-dark bg-dark">

    <div class="container">

        <a class="navbar-brand" routerLink="/products">
            <i class="bi bi-box-seam me-2"></i>
            Angular Signals CRUD
        </a>

    </div>

</nav>

<main>
    <router-outlet></router-outlet>
</main>

Make sure your src/main.ts contains:

import { bootstrapApplication } from '@angular/platform-browser';

import { appConfig } from './app/app.config';
import { App } from './app/app';

bootstrapApplication(App, appConfig)
    .catch(error => console.error(error));

Depending on your Angular CLI version and naming conventions, the generated root component might be named app.component.ts instead of app.ts. Adjust the imports accordingly.

12. Run the application

ng serve

Open:

http://localhost:4200

You should now have a functional CRUD application with reactive search, statistics, validation and persistent browser storage.

13. Understanding CRUD operations with Signals

13.1. Create operation

this.productsSignal.update(products => [
    ...products,
    newProduct
]);

The spread operator creates a new array containing the existing products and the new product.

Before creating

Laptop

Keyboard

Monitor

update(products => […products, newProduct])

After creating — new array

Laptop

Keyboard

Monitor

Mouse

13.2. Read operation

To read all products:

const products = this.productsSignal();

To read a specific product:

const product = this.productsSignal().find(
    product => product.id === id
);

To display the products in an Angular template:

@for (product of products(); track product.id) {

    <div></div>

}

The template reads the signal directly and becomes a reactive consumer of it.

13.3. Update operation

this.productsSignal.update(products =>
    products.map(product =>
        product.id === id
            ? { ...product, ...updatedProduct }
            : product
    )
);

The map() method creates a new array and replaces only the product that matches the specified ID.

Before updating

Laptop$1200

Keyboard$75

Monitor$300

Update product ID 2

After updating

Laptop$1200

Keyboard

$90

Monitor$300

13.4. Delete operation

this.productsSignal.update(products =>
    products.filter(product => product.id !== id)
);

The filter() method creates a new array that excludes the deleted product.

Before deleting

Laptop

Keyboard

Monitor

Delete product ID 2

After deleting

Laptop

Monitor

14. Why immutability is important when using Signals

By default, Angular Signals use referential equality (Object.is) to determine whether a value has changed.

Incorrect approach

this.productsSignal().push(newProduct);

This modifies the existing array without notifying the signal.

Another incorrect approach:

this.productsSignal.update(products => {

    products.push(newProduct);

    return products;
});

The same array reference is returned, so dependent consumers may not be notified.

Correct approach

this.productsSignal.update(products => [
    ...products,
    newProduct
]);

For updating an object:

this.productsSignal.update(products =>
    products.map(product =>
        product.id === id
            ? { ...product, price: 500 }
            : product
    )
);

Always create a new array or object when modifying signal state.

15. Using effect() to persist data automatically

In our original service, we manually call saveProducts() after each CRUD operation.

Angular also provides effect(), which can be used to execute side effects whenever signals change.

Import it:

import {
    Injectable,
    signal,
    computed,
    effect
} from '@angular/core';

Add the following constructor to ProductService:

constructor() {

    effect(() => {

        localStorage.setItem(
            this.storageKey,
            JSON.stringify(this.products())
        );

    });

}

You can then remove the saveProducts() calls from the CRUD methods.

For example, the delete method becomes:

delete(id: number): void {

    this.productsSignal.update(products =>
        products.filter(product => product.id !== id)
    );
}

The effect automatically persists the latest state when it runs.

Effects are particularly useful for logging, browser storage, analytics and integration with non-reactive third-party libraries.

Use computed() rather than effect() when calculating derived state.

Also note that effects are scheduled rather than executed synchronously inside every set() or update() call. Explicit persistence inside CRUD methods is preferable if you require immediate storage writes.

16. Integrating the Angular Signals CRUD with a REST API

For a real-world application, you will probably want to replace localStorage with a REST API, for example one developed using Spring Boot.

The components can continue consuming Signals while the service uses Angular’s HttpClient to communicate with the backend.

16.1. Configure HttpClient

Modify app.config.ts:

import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';

import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {

    providers: [
        provideRouter(routes),
        provideHttpClient()
    ]

};

16.2. REST API endpoints

The backend should expose the following endpoints:

HTTP method Endpoint Operation
GET /api/products Read all products
GET /api/products/{id} Read one product
POST /api/products Create product
PUT /api/products/{id} Update product
DELETE /api/products/{id} Delete product

16.3. Create a REST API service using Signals

The following service demonstrates how to combine Signals with HttpClient and RxJS.

import {
    Injectable,
    inject,
    signal,
    computed
} from '@angular/core';

import { HttpClient } from '@angular/common/http';

import {
    tap,
    finalize,
    catchError,
    throwError
} from 'rxjs';

import {
    Product,
    ProductInput
} from '../models/product.model';

@Injectable({
    providedIn: 'root'
})
export class ProductService {

    private readonly http = inject(HttpClient);

    private readonly apiUrl = 'http://localhost:8080/api/products';

    private readonly productsSignal = signal<Product[]>([]);

    private readonly pendingRequests = signal(0);

    private readonly errorSignal = signal<string | null>(null);

    readonly products = this.productsSignal.asReadonly();

    readonly loading = computed(() =>
        this.pendingRequests() > 0
    );

    readonly error = this.errorSignal.asReadonly();

    readonly totalProducts = computed(() =>
        this.products().length
    );

    readonly totalQuantity = computed(() =>
        this.products().reduce(
            (total, product) => total + product.quantity,
            0
        )
    );

    readonly totalValue = computed(() =>
        this.products().reduce(
            (total, product) =>
                total + product.price * product.quantity,
            0
        )
    );

    // READ ALL

    loadProducts() {

        return this.http.get<Product[]>(this.apiUrl).pipe(

            tap(products => {
                this.productsSignal.set(products);
            })

        );
    }

    // READ ONE

    getById(id: number) {

        return this.http.get<Product>(
            `${this.apiUrl}/${id}`
        );
    }

    // CREATE

    create(product: ProductInput) {

        return this.http.post<Product>(
            this.apiUrl,
            product
        ).pipe(

            tap(newProduct => {

                this.productsSignal.update(products => [
                    ...products,
                    newProduct
                ]);

            })

        );
    }

    // UPDATE

    update(id: number, product: ProductInput) {

        return this.http.put<Product>(
            `${this.apiUrl}/${id}`,
            product
        ).pipe(

            tap(updatedProduct => {

                this.productsSignal.update(products =>
                    products.map(p =>
                        p.id === id ? updatedProduct : p
                    )
                );

            })

        );
    }

    // DELETE

    delete(id: number) {

        return this.http.delete<void>(
            `${this.apiUrl}/${id}`
        ).pipe(

            tap(() => {

                this.productsSignal.update(products =>
                    products.filter(p => p.id !== id)
                );

            })

        );
    }

    // Track loading and error state for HTTP requests

    execute<T>(request: import('rxjs').Observable<T>) {

        return import('rxjs').then(({ defer }) =>
            defer(() => {

                this.pendingRequests.update(count => count + 1);
                this.errorSignal.set(null);

                return request.pipe(

                    catchError(error => {

                        this.errorSignal.set(
                            'The request could not be completed.'
                        );

                        return throwError(() => error);
                    }),

                    finalize(() => {
                        this.pendingRequests.update(count => count - 1);
                    })

                );
            })
        );
    }
}

For normal Angular code, you can simplify the execute() method by importing Observable and defer statically from RxJS. This is the preferred implementation:

import { Observable, defer } from 'rxjs';
execute<T>(request: Observable<T>): Observable<T> {

    return defer(() => {

        this.pendingRequests.update(count => count + 1);
        this.errorSignal.set(null);

        return request.pipe(

            catchError(error => {

                this.errorSignal.set(
                    'The request could not be completed.'
                );

                return throwError(() => error);
            }),

            finalize(() => {
                this.pendingRequests.update(count => count - 1);
            })

        );
    });
}

Use this second version of execute() in the actual service.

16.4. Load products from the REST API

Modify the product list component to load products when it is initialized.

export class ProductListComponent implements OnInit {

    private readonly productService = inject(ProductService);

    readonly products = this.productService.products;

    readonly loading = this.productService.loading;

    readonly error = this.productService.error;

    ngOnInit(): void {

        this.productService.execute(
            this.productService.loadProducts()
        ).subscribe({
            error: error => console.error(error)
        });

    }

    // Remaining component code...
}

Remember to import OnInit from @angular/core.

In the HTML template, display the loading and error states:

@if (loading()) {

    <div class="text-center py-4">

        <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">Loading...</span>
        </div>

    </div>

} @else if (error()) {

    <div class="alert alert-danger" role="alert">
        
    </div>

} @else {

    <!-- Product table -->

}

16.5. Create and update products asynchronously

When using a REST API, the form must wait until the HTTP request completes successfully before navigating back to the product list.

Replace the synchronous CRUD calls inside onSubmit() with:

const id = this.productId();

const request = id !== null
    ? this.productService.update(id, product)
    : this.productService.create(product);

this.productService.execute(request).subscribe({

    next: () => {
        this.router.navigate(['/products']);
    },

    error: error => {
        console.error(error);
    }

});

The form’s ngOnInit() must also load the existing product asynchronously in edit mode:

ngOnInit(): void {

    const id = this.route.snapshot.paramMap.get('id');

    if (id !== null) {

        this.productService.execute(
            this.productService.getById(Number(id))
        ).subscribe({

            next: product => {

                this.productId.set(product.id);

                this.productForm.patchValue({
                    name: product.name,
                    price: product.price,
                    quantity: product.quantity
                });

            },

            error: error => {
                console.error(error);
                this.router.navigate(['/products']);
            }

        });

    }
}

Expose the loading and error signals in the form component:

readonly loading = this.productService.loading;
readonly error = this.productService.error;

Disable the submit button while an HTTP request is running:

<button
    type="submit"
    class="btn btn-primary"
    [disabled]="loading()"
>
    @if (loading()) {
        Saving...
    } @else {
        Save product
    }
</button>

16.6. Delete products asynchronously

deleteProduct(product: Product): void {

    if (!confirm(`Delete ${product.name}?`)) {
        return;
    }

    this.productService.execute(
        this.productService.delete(product.id)
    ).subscribe({

        error: error => {
            console.error(error);
        }

    });
}

REST API architecture

Signals do not need to replace RxJS completely. They work very well together: RxJS handles asynchronous HTTP operations, while Signals handle reactive application state.

For the REST API version, the backend must return the created or updated product in the POST and PUT responses, generate product IDs, validate submitted data and permit the frontend origin through CORS or an Angular development proxy.

17. Signals vs RxJS BehaviorSubject

Here is a comparison between the traditional RxJS approach and the Signals approach.

Operation BehaviorSubject Signals
Initialize state new BehaviorSubject([]) signal([])
Read current value .getValue() products()
Replace value .next(value) .set(value)
Modify value .next(newValue) .update(callback)
Derived state map(), combineLatest() computed()
Side effects .subscribe() effect()
Read in template products$ \\| async products()
Manual subscription for state Sometimes Not required
Async HTTP operations Excellent Usually combined with RxJS
Debouncing and cancellation Built-in RxJS operators Usually combined with RxJS

Traditional BehaviorSubject implementation

private productsSubject =
    new BehaviorSubject<Product[]>([]);

products$ = this.productsSubject.asObservable();

create(product: Product): void {

    const products = this.productsSubject.getValue();

    this.productsSubject.next([
        ...products,
        product
    ]);
}

Signals implementation

private productsSignal = signal<Product[]>([]);

readonly products = this.productsSignal.asReadonly();

create(product: Product): void {

    this.productsSignal.update(products => [
        ...products,
        product
    ]);
}

The Signals implementation is simpler for synchronous application state.

18. Summary of Angular Signals APIs

API Description Writable
signal() Creates reactive state Yes
set() Replaces the signal value Yes
update() Modifies state using its previous value Yes
asReadonly() Exposes a read-only signal No
computed() Calculates derived reactive state No
effect() Executes reactive side effects N/A
untracked() Reads signals without tracking dependencies N/A
linkedSignal() Creates writable state linked to reactive dependencies Yes
toSignal() Converts an Observable into a Signal No
toObservable() Converts a Signal into an Observable N/A

19. Recommended approach for real-world Angular applications

For an Angular frontend communicating with Spring Boot REST APIs, I recommend the following architecture:

Responsibility Recommended technology
Components Standalone components
Application state Signals
Derived state computed()
HTTP requests HttpClient and RxJS
Form management Typed Reactive Forms
Dependency injection inject()
Routing Lazy-loaded standalone components
Change detection OnPush
Styling Bootstrap 5
Directory structure Feature-based
Complex application state NgRx SignalStore, when necessary
Backend Spring Boot REST API
Database MySQL

For small and medium-sized CRUD applications, a service containing private writable signals and public read-only signals is generally sufficient. You do not need to introduce NgRx just to manage CRUD operations.

Implementation notes: I chose a product inventory application, Bootstrap 5, Reactive Forms and browser storage because no specific entity, styling framework or backend was requested. The REST API section is an optional adaptation. The code has not been compiled or tested against your installed Angular version, and the interactive preview is a simulation rather than a running Angular application.

Newer >>