This is a comprehensive request to build an Angular app with NgRx implementing optimistic UI updates. I'll need to create:
- NgRx store setup (state, actions, reducers, effects)
- A service to handle API calls
- Components to display items
- Toast notification system
- Optimistic deletion with rollback on failure
- Proper error handling
Let me structure this properly with all the necessary files:
-
Store:
- State interface
- Actions (delete, delete success, delete failure)
- Reducer (handle optimistic delete, rollback)
- Effects (handle API call)
- Selectors
-
Services:
- API service
- Toast/Notification service
-
Components:
- Item list component
- Item component
-
Models:
Let me build a complete, production-ready example.
Angular NgRx Optimistic UI Updates with Rollback
I'll create a complete example with NgRx store, effects, and optimistic deletion with rollback functionality.
1. Project Setup & Dependencies
ng new ngrx-optimistic-app
cd ngrx-optimistic-app
npm install @ngrx/store @ngrx/effects @ngrx/entity @ngrx/store-devtools
2. Models & Interfaces
// src/app/models/item.model.ts
export interface Item {
id: string;
title: string;
description: string;
completed: boolean;
isDeleting?: boolean;
}
export interface ItemsState {
items: Item[];
loading: boolean;
error: string | null;
}
export interface ToastNotification {
id: string;
message: string;
type: 'success' | 'error' | 'warning' | 'info';
duration?: number;
}
3. NgRx Store Setup
State & Selectors
// src/app/store/items/items.state.ts
import { createEntityAdapter, EntityAdapter, EntityState } from '@ngrx/entity';
import { Item } from '../../models/item.model';
export interface ItemsState extends EntityState<Item> {
loading: boolean;
error: string | null;
}
export const itemsAdapter: EntityAdapter<Item> = createEntityAdapter<Item>({
selectId: (item: Item) => item.id,
});
export const initialItemsState: ItemsState = itemsAdapter.getInitialState({
loading: false,
error: null,
});
Actions
// src/app/store/items/items.actions.ts
import { createAction, props } from '@ngrx/store';
import { Item } from '../../models/item.model';
// Load Items
export const loadItems = createAction('[Items] Load Items');
export const loadItemsSuccess = createAction(
'[Items] Load Items Success',
props<{ items: Item[] }>()
);
export const loadItemsFailure = createAction(
'[Items] Load Items Failure',
props<{ error: string }>()
);
// Add Item
export const addItem = createAction(
'[Items] Add Item',
props<{ item: Item }>()
);
export const addItemSuccess = createAction(
'[Items] Add Item Success',
props<{ item: Item }>()
);
export const addItemFailure = createAction(
'[Items] Add Item Failure',
props<{ error: string }>()
);
// Delete Item - OPTIMISTIC
export const deleteItem = createAction(
'[Items] Delete Item',
props<{ id: string }>()
);
export const deleteItemOptimistic = createAction(
'[Items] Delete Item Optimistic',
props<{ id: string; deletedItem: Item }>()
);
export const deleteItemSuccess = createAction(
'[Items] Delete Item Success',
props<{ id: string }>()
);
export const deleteItemFailure = createAction(
'[Items] Delete Item Failure',
props<{ id: string; deletedItem: Item; error: string }>()
);
// Update Item
export const updateItem = createAction(
'[Items] Update Item',
props<{ item: Item }>()
);
export const updateItemSuccess = createAction(
'[Items] Update Item Success',
props<{ item: Item }>()
);
export const updateItemFailure = createAction(
'[Items] Update Item Failure',
props<{ error: string }>()
);
// Clear Error
export const clearError = createAction('[Items] Clear Error');
Reducer
// src/app/store/items/items.reducer.ts
import { createReducer, on } from '@ngrx/store';
import * as ItemsActions from './items.actions';
import { ItemsState, itemsAdapter, initialItemsState } from './items.state';
export const itemsReducer = createReducer(
initialItemsState,
// Load Items
on(ItemsActions.loadItems, (state) => ({
...state,
loading: true,
error: null,
})),
on(ItemsActions.loadItemsSuccess, (state, { items }) =>
itemsAdapter.setAll(items, {
...state,
loading: false,
})
),
on(ItemsActions.loadItemsFailure, (state, { error }) => ({
...state,
loading: false,
error,
})),
// Add Item
on(ItemsActions.addItem, (state) => ({
...state,
loading: true,
})),
on(ItemsActions.addItemSuccess, (state, { item }) =>
itemsAdapter.addOne(item, {
...state,
loading: false,
})
),
on(ItemsActions.addItemFailure, (state, { error }) => ({
...state,
loading: false,
error,
})),
// Delete Item - Optimistic
on(ItemsActions.deleteItemOptimistic, (state, { id }) =>
itemsAdapter.removeOne(id, state)
),
on(ItemsActions.deleteItemSuccess, (state, { id }) => state),
on(ItemsActions.deleteItemFailure, (state, { id, deletedItem }) =>
itemsAdapter.addOne(deletedItem, state)
),
// Update Item
on(ItemsActions.updateItem, (state) => ({
...state,
loading: true,
})),
on(ItemsActions.updateItemSuccess, (state, { item }) =>
itemsAdapter.updateOne(
{ id: item.id, changes: item },
{
...state,
loading: false,
}
)
),
on(ItemsActions.updateItemFailure, (state, { error }) => ({
...state,
loading: false,
error,
})),
// Clear Error
on(ItemsActions.clearError, (state) => ({
...state,
error: null,
}))
);
Selectors
// src/app/store/items/items.selectors.ts
import { createFeatureSelector, createSelector } from '@ngrx/store';
import { ItemsState, itemsAdapter } from './items.state';
export const selectItemsState = createFeatureSelector<ItemsState>('items');
export const selectAllItems = createSelector(selectItemsState, itemsAdapter.selectAll);
export const selectItemsLoading = createSelector(
selectItemsState,
(state) => state.loading
);
export const selectItemsError = createSelector(
selectItemsState,
(state) => state.error
);
export const selectItemById = (id: string) =>
createSelector(selectItemsState, (state) => {
return state.entities[id];
});
export const selectItemCount = createSelector(
selectItemsState,
(state) => state.ids.length
);
export const selectCompletedItemCount = createSelector(selectAllItems, (items) =>
items.filter((item) => item.completed).length
);
Effects
// src/app/store/items/items.effects.ts
import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { of } from 'rxjs';
import { map, switchMap, catchError, tap } from 'rxjs/operators';
import * as ItemsActions from './items.actions';
import { ItemsService } from '../../services/items.service';
import { ToastService } from '../../services/toast.service';
@Injectable()
export class ItemsEffects {
loadItems$ = createEffect(() =>
this.actions$.pipe(
ofType(ItemsActions.loadItems),
switchMap(() =>
this.itemsService.getItems().pipe(
map((items) => ItemsActions.loadItemsSuccess({ items })),
catchError((error) =>
of(
ItemsActions.loadItemsFailure({
error: error.message || 'Failed to load items',
})
)
)
)
)
)
);
addItem$ = createEffect(() =>
this.actions$.pipe(
ofType(ItemsActions.addItem),
switchMap(({ item }) =>
this.itemsService.addItem(item).pipe(
map((createdItem) =>
ItemsActions.addItemSuccess({ item: createdItem })
),
catchError((error) =>
of(
ItemsActions.addItemFailure({
error: error.message || 'Failed to add item',
})
)
)
)
)
)
);
// Optimistic Delete Effect
deleteItem$ = createEffect(() =>
this.actions$.pipe(
ofType(ItemsActions.deleteItem),
switchMap(({ id }) =>
// Get the item before deletion for rollback
this.itemsService.getItemById(id).pipe(
switchMap((deletedItem) =>
// Dispatch optimistic action first
this.actions$.pipe(
ofType(
ItemsActions.deleteItemOptimistic({ id, deletedItem })
),
switchMap(() =>
this.itemsService.deleteItem(id).pipe(
map(() => ItemsActions.deleteItemSuccess({ id })),
catchError((error) => {
const errorMessage =
error.message || 'Failed to delete item';
this.toastService.showError(errorMessage);
return of(
ItemsActions.deleteItemFailure({
id,
deletedItem,
error: errorMessage,
})
);
})
)
)
)
),
catchError((error) =>
of(
ItemsActions.deleteItemFailure({
id,
deletedItem: { id } as any,
error: error.message || 'Failed to delete item',
})
)
)
)
)
)
);
// Simpler version - dispatch optimistic directly
deleteItemOptimistic$ = createEffect(() =>
this.actions$.pipe(
ofType(ItemsActions.deleteItemOptimistic),
switchMap(({ id, deletedItem }) =>
this.itemsService.deleteItem(id).pipe(
map(() => ItemsActions.deleteItemSuccess({ id })),
catchError((error) => {
this.toastService.showError(
error.message || 'Failed to delete item. Changes reverted.'
);
return of(
ItemsActions.deleteItemFailure({
id,
deletedItem,
error: error.message || 'Failed to delete item',
})
);
})
)
)
)
);
deleteItemSuccess$ = createEffect(
() =>
this.actions$.pipe(
ofType(ItemsActions.deleteItemSuccess),
tap(() => this.toastService.showSuccess('Item deleted successfully'))
),
{ dispatch: false }
);
updateItem$ = createEffect(() =>
this.actions$.pipe(
ofType(ItemsActions.updateItem),
switchMap(({ item }) =>
this.itemsService.updateItem(item).pipe(
map((updatedItem) =>
ItemsActions.updateItemSuccess({ item: updatedItem })
),
catchError((error) =>
of(
ItemsActions.updateItemFailure({
error: error.message || 'Failed to update item',
})
)
)
)
)
)
);
handleError$ = createEffect(
() =>
this.actions$.pipe(
ofType(
ItemsActions.loadItemsFailure,
ItemsActions.addItemFailure,
ItemsActions.updateItemFailure
),
tap(({ error }) => this.toastService.showError(error))
),
{ dispatch: false }
);
constructor(
private actions$: Actions,
private itemsService: ItemsService,
private toastService: ToastService
) {}
}
4. Services
Items Service
// src/app/services/items.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, delay } from 'rxjs/operators';
import { Item } from '../models/item.model';
@Injectable({
providedIn: 'root',
})
export class ItemsService {
private apiUrl = 'http://localhost:3000/api/items';
constructor(private http: HttpClient) {}
getItems(): Observable<Item[]> {
return this.http.get<Item[]>(this.apiUrl).pipe(
delay(500), // Simulate network delay
catchError(this.handleError)
);
}
getItemById(id: string): Observable<Item> {
return this.http.get<Item>(`${this.apiUrl}/${id}`).pipe(
catchError(this.handleError)
);
}
addItem(item: Item): Observable<Item> {
return this.http.post<Item>(this.apiUrl, item).pipe(
delay(500),
catchError(this.handleError)
);
}
updateItem(item: Item): Observable<Item> {
return this.http.put<Item>(`${this.apiUrl}/${item.id}`, item).pipe(
delay(500),
catchError(this.handleError)
);
}
deleteItem(id: string): Observable<void> {
return this.http.delete<void>(`${this.apiUrl}/${id}`).pipe(
delay(500),
catchError(this.handleError)
);
}
private handleError(error: HttpErrorResponse) {
let errorMessage = 'An unknown error occurred';
if (error.error instanceof ErrorEvent) {
errorMessage = `Error: ${error.error.message}`;
} else {
errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
}
return throwError(() => new Error(errorMessage));
}
}
Toast Service
// src/app/services/toast.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { v4 as uuid } from 'uuid';
import { ToastNotification } from '../models/item.model';
@Injectable({
providedIn: 'root',
})
export class ToastService {
private toasts$ = new BehaviorSubject<ToastNotification[]>([]);
getToasts(): Observable<ToastNotification[]> {
return this.toasts$.asObservable();
}
showSuccess(message: string, duration: number = 3000): void {
this.show({
id: uuid(),
message,
type: 'success',
duration,
});
}
showError(message: string, duration: number = 5000): void {
this.show({
id: uuid(),
message,
type: 'error',
duration,
});
}
showWarning(message: string, duration: number = 4000): void {
this.show({
id: uuid(),
message,
type: 'warning',
duration,
});
}
showInfo(message: string, duration: number = 3000): void {
this.show({
id: uuid(),
message,
type: 'info',
duration,
});
}
private show(notification: ToastNotification): void {
const currentToasts = this.toasts$.value;
this.toasts$.next([...currentToasts, notification]);
if (notification.duration && notification.duration > 0) {
setTimeout(() => this.remove(notification.id), notification.duration);
}
}
remove(id: string): void {
const updatedToasts = this.toasts$.value.filter((t) => t.id !== id);
this.toasts$.next(updatedToasts);
}
clearAll(): void {
this.toasts$.next([]);
}
}
5. Components
Toast Component
// src/app/components/toast/toast.component.ts
import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { trigger, transition, style, animate } from '@angular/animations';
import { ToastService } from '../../services/toast.service';
import { ToastNotification } from '../../models/item.model';
import { Observable } from 'rxjs';
@Component({
selector: 'app-toast',
standalone: true,
imports: [CommonModule],
template: `
<div class="toast-container">
<div
*ngFor="let toast of toasts$ | async"
[@slideInOut]
[class]="'toast toast-' + toast.type"
>
<div class="toast-content">
<span class="toast-icon">
{{ getIcon(toast.type) }}
</span>
<span class="toast-message">{{ toast.message }}</span>
<button
class="toast-close"
(click)="closeToast(toast.id)"
aria-label="Close"
>
×
</button>
</div>
<div class="toast-progress">
<div class="toast-progress-bar"></div>
</div>
</div>
</div>
`,
styles: [
`
.toast-container {
position: fixed;
top: 20px;
right: 20px;
z-index: 9999;
display: flex;
flex-direction: column;
gap: 10px;
max-width: 400px;
}
.toast {
padding: 16px;
border-radius: 4px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
display: flex;
flex-direction: column;
gap: 8px;
font-size: 14px;
line-height: 1.5;
}
.toast-content {
display: flex;
align-items: center;
gap: 12px;
}
.toast-icon {
font-size: 18px;
flex-shrink: 0;
}
.toast-message {
flex: 1;
word-break: break-word;
}
.toast-close {
background: none;
border: none;
font-size: 24px;
cursor: pointer;
padding: 0;
margin: 0;
opacity: 0.7;
transition: opacity 0.2s;
display: flex;
align-items: center;
justify-content: center;
width: 24px;
height: 24px;
}
.toast-close:hover {
opacity: 1;
}
.toast-success {
background-color: #d4edda;
color: #155724;
border: 1px solid #c3e6cb;
}
.toast-error {
background-color: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
}
.toast-warning {
background-color: #fff3cd;
color: #856404;
border: 1px solid #ffeeba;
}
.toast-info {
background-color: #d1ecf1;
color: #0c5460;
border: 1px solid #bee5eb;
}
.toast-progress {
height: 2px;
background-color: rgba(0, 0, 0, 0.1);
border-radius: 1px;
overflow: hidden;
}
.toast-progress-bar {
height: 100%;
background-color: currentColor;
opacity: 0.5;
animation: progress 3s linear forwards;
}
@keyframes progress {
from {
width: 100%;
}
to {
width: 0%;
}
}
`,
],
animations: [
trigger('slideInOut', [
transition(':enter', [
style({ transform: 'translateX(400px)', opacity: 0 }),
animate('300ms ease-out', style({ transform: 'translateX(0)', opacity: 1 })),
]),
transition(':leave', [
animate('300ms ease-in', style({ transform: 'translateX(400px)', opacity: 0 })),
]),
]),
],
})
export class ToastComponent implements OnInit {
toasts$: Observable<ToastNotification[]>;
constructor(private toastService: ToastService) {
this.toasts$ = this.toastService.getToasts();
}
ngOnInit(): void {}
closeToast(id: string): void {
this.toastService.remove(id);
}
getIcon(type: string): string {
const icons = {
success: '✓',
error: '✕',
warning: '⚠',
info: 'ℹ',
};
return icons[type as keyof typeof icons] || '•';
}
}
Items List Component
// src/app/components/items-list/items-list.component.ts
import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { Observable } from 'rxjs';
import { Store } from '@ngrx/store';
import * as ItemsActions from '../../store/items/items.actions';
import * as ItemsSelectors from '../../store/items/items.selectors';
import { Item } from '../../models/item.model';
import { v4 as uuid } from 'uuid';
@Component({
selector: 'app-items-list',
standalone: true,
imports: [CommonModule, FormsModule],
template: `
<div class="items-container">
<div class="items-header">
<h1>Items Manager</h1>
<p class="item-count">Total: {{ (itemCount$ | async) || 0 }} items</p>
</div>
<div class="add-item-form">
<input
v-model="newItemTitle"
[(ngModel)]="newItemTitle"
type="text"
placeholder="Enter item title..."
(keyup.enter)="addItem()"
class="input-field"
/>
<button (click)="addItem()" class="btn btn-primary">
Add Item
</button>
</div>
<div class="loading" *ngIf="loading$ | async">
<div class="spinner"></div>
<p>Loading items...</p>
</div>
<div class="error" *ngIf="error$ | async as error">
<p>{{ error }}</p>
<button (click)="clearError()" class="btn btn-secondary">
Dismiss
</button>
</div>
<div class="items-list">
<div *ngIf="(items$ | async)?.length === 0" class="empty-state">
<p>No items yet. Create one to get started!</p>
</div>
<div
*ngFor="let item of items$ | async"
[class]="'item-card'"
[@itemAnimation]
>
<div class="item-content">
<input
type="checkbox"
[checked]="item.completed"
(change)="toggleComplete(item)"
class="checkbox"
[disabled]="item.isDeleting"
/>
<div class="item-text">
<h3 [class.completed]="item.completed">{{ item.title }}</h3>
<p *ngIf="item.description">{{ item.description }}</p>
</div>
</div>
<div class="item-actions">
<button
(click)="deleteItem(item)"
[disabled]="item.isDeleting"
class="btn btn-danger"
[attr.aria-label]="'Delete ' + item.title"
>
<span *ngIf="!item.isDeleting">Delete</span>
<span *ngIf="item.isDeleting">
<span class="mini-spinner"></span>
</span>
</button>
</div>
</div>
</div>
</div>
`,
styles: [
`
.items-container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
'Helvetica Neue', Arial, sans-serif;
}
.items-header {
margin-bottom: 30px;
text-align: center;
}
.items-header h1 {
margin: 0 0 10px 0;
font-size: 32px;
color: #333;
}
.item-count {
margin: 0;
color: #666;
font-size: 14px;
}
.add-item-form {
display: flex;
gap: 10px;
margin-bottom: 30px;
}
.input-field {
flex: 1;
padding: 12px;
border: 2px solid #ddd;
border-radius: 4px;
font-size: 16px;
transition: border-color 0.3s;
}
.input-field:focus {
outline: none;
border-color: #007bff;
}
.btn {
padding: 12px 24px;
border: none;
border-radius: 4px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s;
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
}
.btn-primary {
background-color: #007bff;
color: white;
}
.btn-primary:hover:not(:disabled) {
background-color: #0056b3;
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0, 123, 255, 0.3);
}
.btn-danger {
background-color: #dc3545;
color: white;
padding: 8px 16px;
font-size: 14px;
}
.btn-danger:hover:not(:disabled) {
background-color: #c82333;
}
.btn-danger:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.btn-secondary {
background-color: #6c757d;
color: white;
}
.btn-secondary:hover {
background-color: #5a6268;
}
.loading {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 16px;
padding: 40px;
text-align: center;
}
.spinner {
width: 40px;
height: 40px;
border: 4px solid #f3f3f3;
border-top: 4px solid #007bff;
border-radius: 50%;
animation: spin 1s linear infinite;
}
.mini-spinner {
display: inline-block;
width: 16px;
height: 16px;
border: 2px solid rgba(255, 255, 255, 0.3);
border-top: 2px solid white;
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
.error {
padding: 16px;
background-color: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
border-radius: 4px;
margin-bottom: 20px;
display: flex;
justify-content: space-between;
align-items: center;
}
.error p {
margin: 0;
}
.items-list {
display: flex;
flex-direction: column;
gap: 12px;
}
.empty-state {
text-align: center;
padding: 40px;
color: #999;
}
.item-card {
display: flex;
justify-content: space-between;
align-items: center;
padding: 16px;
background-color: #fff;
border: 1px solid #ddd;
border-radius: 4px;
transition: all 0.3s;
}
.item-card:hover {
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
border-color: #bbb;
}
.item-content {
display: flex;
align-items: flex-start;
gap: 12px;
flex: 1;
}
.checkbox {
width: 20px;
height: 20px;
margin-top: 2px;
cursor: pointer;
flex-shrink: 0;
}
.item-text {
flex: 1;
}
.item-text h3 {
margin: 0 0 4px 0;
font-size: 16px;
font-weight: 600;
color: #333;
}
.item-text h3.completed {
color: #999;
text-decoration: line-through;
}
.item-text p {
margin: 4px 0 0 0;
color: #666;
font-size: 14px;
}
.item-actions {
display: flex;
gap: 8px;
}
`,
],
})
export class ItemsListComponent implements OnInit {
items$: Observable<Item[]>;
loading$: Observable<boolean>;
error$: Observable<string | null>;
itemCount$: Observable<number>;
newItemTitle: string = '';
constructor(private store: Store) {
this.items$ = this.store.select(ItemsSelectors.selectAllItems);
this.loading$ = this.store.select(ItemsSelectors.selectItemsLoading);
this.error$ = this.store.select(ItemsSelectors.selectItemsError);
this.itemCount$ = this.store.select(ItemsSelectors.selectItemCount);
}
ngOnInit(): void {
this.store.dispatch(ItemsActions.loadItems());
}
addItem(): void {
if (!this.newItemTitle.trim()) {
return;
}
const newItem: Item = {
id: uuid(),
title: this.newItemTitle,
description: '',
completed: false,
};
this.store.dispatch(ItemsActions.addItem({ item: newItem }));
this.newItemTitle = '';
}
deleteItem(item: Item): void {
// Store the item for potential rollback
const deletedItem = { ...item };
// Dispatch optimistic delete - immediately removes from UI
this.store.dispatch(
ItemsActions.deleteItemOptimistic({
id: item.id,
deletedItem,
})
);
}
toggleComplete(item: Item): void {
const updatedItem = { ...item, completed: !item.completed };
this.store.dispatch(ItemsActions.updateItem({ item: updatedItem }));
}
clearError(): void {
this.store.dispatch(ItemsActions.clearError());
}
}
6. Store Configuration
// src/app/store/app.state.ts
import { ItemsState } from './items/items.state';
export interface AppState {
items: ItemsState;
}
7. App Module Setup
// src/app/app.config.ts
import { ApplicationConfig, importProvidersFrom } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { StoreModule } from '@ngrx/store';
import { EffectsModule } from '@ngrx/effects';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { itemsReducer } from './store/items/items.reducer';
import { ItemsEffects } from './store/items/items.effects';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(),
StoreModule.forRoot({
items: itemsReducer,
}),
EffectsModule.forRoot([ItemsEffects]),
StoreDevtoolsModule.instrument({
maxAge: 25,
logOnly: false,
}),
],
};
// src/app/app.component.ts
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ItemsListComponent } from './components/items-list/items-list.component';
import { ToastComponent } from './components/toast/toast.component';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule, ItemsListComponent, ToastComponent],
template: `
<app-toast></app-toast>
<app-items-list></app-items-list>
`,
styles: [
`
:host {
display: block;
background-color: #f5f5f5;
min-height: 100vh;
}
`,
],
})
export class AppComponent {}
8. Mock Backend (Optional - for testing)
// src/app/services/mock-backend.interceptor.ts
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor,
HttpResponse,
} from '@angular/common/http';
import { Observable, of, throwError } from 'rxjs';
import { delay } from 'rxjs/operators';
@Injectable()
export class MockBackendInterceptor implements HttpInterceptor {
private items = [
{
id: '1',
title: 'Learn Angular',
description: 'Study Angular fundamentals',
completed: false,
},
{
id: '2',
title: 'Master NgRx',
description: 'Learn state management with NgRx',
completed: false,
},
{
id: '3',
title: 'Build an app',
description: 'Create a real-world application',
completed: false,
},
];
intercept(
request: HttpRequest<unknown>,
next: HttpHandler
): Observable<HttpEvent<unknown>> {
const { url, method, body } = request;
if (url.includes('/api/items') && method === 'GET' && !url.includes('/')) {
return of(new HttpResponse({ status: 200, body: this.items })).pipe(
delay(500)
);
}
if (url.match(/\/api\/items\/\w+$/) && method === 'GET') {
const id = url.split('/').pop();
const item = this.items.find((i) => i.id === id);
return item
? of(new HttpResponse({ status: 200, body: item })).pipe(delay(300))
: throwError(() => new Error('Item not found'));
}
if (url.includes('/api/items') && method === 'POST') {
const newItem = { ...body, id: Date.now().toString() };
this.items.push(newItem);
return of(new HttpResponse({ status: 201, body: newItem })).pipe(
delay(500)
);
}
if (url.match(/\/api\/items\/\w+$/) && method === 'DELETE') {
const id = url.split('/').pop();
this.items = this.items.filter((i) => i.id !== id);
return of(new HttpResponse({ status: 204 })).pipe(delay(500));
}
if (url.match(/\/api\/items\/\w+$/) && method === 'PUT') {
const id = url.split('/').pop();
const index = this.items.findIndex((i) => i.id === id);
if (index > -1) {
this.items[index] = { ...body, id };
return of(new HttpResponse({ status: 200, body: this.items[index] })).pipe(
delay(500)
);
}
}
return next.handle(request);
}
}
Add to app.config.ts:
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { MockBackendInterceptor } from './services/mock-backend.interceptor';
export const appConfig: ApplicationConfig = {
providers: [
// ... other providers
{
provide: HTTP_INTERCEPTORS,
useClass: MockBackendInterceptor,
multi: true,
},
],
};
Key Features Implemented:
✅ Optimistic Deletion - Item removed from UI immediately
✅ Automatic Rollback - Item restored if API call fails
✅ Toast Notifications - Success and error messages
✅ State Management - NgRx store with effects
✅ Loading States - UI feedback during operations
✅ Error Handling - Graceful error management
✅ Animation - Smooth transitions for items and toasts
✅ Standalone Components - Modern Angular setup
✅ Entity Adapter - Efficient state normalization
✅ Type Safety - Full TypeScript support
This implementation provides a production-ready solution with proper optimistic UI patterns!