Skip to content
Tutorials Center
My learning

Topics

Lesson 74 of 74 ยท Practice and Review

Angular Cheat Sheet

A one-page Angular cheat sheet for modern Angular - CLI commands, template syntax, control flow, signals, DI, routing, forms, HttpClient, RxJS operators and testing snippets.

This is the page to keep open in a tab. It does not replace the lessons: each section links to the lesson that explains the idea in full. Think of it as a map. You will know most of what is on it, and when you do not, you will know where to read.

Everything targets modern Angular (20 and later): standalone components, signals, built-in control flow and inject(). Older code uses NgModule, *ngIf, @Input() and constructor injection; they still work, but new code should use the forms shown here.

Real Angular vs stand-in. All Angular snippets below are real and read-only, because the site cannot run Angular's compiler or CLI. The two runnable examples at the end are hand-written TypeScript stand-ins for RxJS-style operators and for route matching. Check the details of experimental APIs (signal forms, resource) in the docs for your version.

CLI commands

Command What it does
npm install -g @angular/cli Installs the CLI
ng new my-app Creates a workspace with a standalone app
ng serve Dev server with live reload (default port 4200)
ng build Production build into dist/
ng test Runs unit tests with the configured test runner
ng generate component user-card (ng g c ...) New component (also service, pipe, directive, guard, interceptor)
ng add <package> Installs a package and runs its setup
ng update Updates Angular and runs migrations
ng extract-i18n Extracts translatable text

See Setup and the Angular CLI and Building and Deploying.

Component skeleton

TypeScript
import { ChangeDetectionStrategy, Component, computed, input, output, signal } from '@angular/core';

@Component({
  selector: 'app-counter',
  imports: [],
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <button type="button" (click)="increment()">{{ label() }}: {{ count() }}</button>
    <p>Double: {{ double() }}</p>
  `,
  styles: `button { font-weight: bold; }`,
})
export class Counter {
  label = input('Clicks'); // input with a default
  start = input.required<number>(); // required input
  changed = output<number>(); // output

  count = signal(0);
  double = computed(() => this.count() * 2);

  increment(): void {
    this.count.update((value) => value + 1);
    this.changed.emit(this.count());
  }
}

See Your First Component and Inputs and Outputs.

Template syntax

Syntax Meaning
{{ user.name }} Interpolation
[disabled]="busy()" Property binding
[attr.aria-label]="text" Attribute binding
[class.active]="isActive()" Toggle one class
[style.width.px]="width()" Set one style with a unit
(click)="save($event)" Event binding
(keydown.enter)="send()" Key-filtered event
[(ngModel)]="name" Two-way binding (needs FormsModule)
[(value)]="size" Two-way binding with a model() signal
#box Template reference variable
{{ price | currency }} Pipe
user?.name, a ?? b Safe navigation, nullish coalescing
@let total = price() * qty(); Template-local variable

See Interpolation, Property binding, Event binding and Two-way binding.

Control flow

HTML
@if (user(); as u) {
  <p>Hello, {{ u.name }}</p>
} @else if (loading()) {
  <p>Loading...</p>
} @else {
  <a routerLink="/login">Sign in</a>
}

@for (item of items(); track item.id; let i = $index, last = $last) {
  <li>{{ i + 1 }}. {{ item.title }}</li>
} @empty {
  <li>Nothing here yet.</li>
}

@switch (status()) {
  @case ('ok') { <span>Done</span> }
  @case ('error') { <span>Failed</span> }
  @default { <span>Unknown</span> }
}

@defer (on viewport) {
  <app-heavy-chart />
} @placeholder {
  <p>Chart placeholder</p>
} @loading (minimum 300ms) {
  <p>Loading chart...</p>
}

@for always needs track (use a stable id). Implicit variables: $index, $count, $first, $last, $even, $odd. See Control Flow and Deferrable Views.

flowchart LR
  T["Template<br/>(HTML + bindings)"] --> C["Compiler<br/>(build time)"]
  C --> I["Instructions<br/>in JavaScript"]
  I --> R["Runtime updates<br/>only changed bindings"]

Angular compiles templates ahead of time, so the browser runs generated instructions, not your HTML text.

Signals API

API Purpose
signal(0) Writable state; read with count()
.set(v), .update(fn) Replace or derive the next value
.asReadonly() Expose read-only access
computed(() => a() + b()) Lazy, memoized derived value
effect(() => ...) Side effects when read signals change (injection context)
untracked(() => x()) Read without creating a dependency
linkedSignal(() => src()[0]) Derived but writable, resets with the source
input(), input.required() Signal inputs
model() Two-way signal input
viewChild(), viewChildren() Signal queries
toSignal(obs$) / toObservable(sig) Bridge to RxJS
resource({ params, loader }) Async data driven by signals (check status in your version)

Replace arrays and objects instead of mutating them. See Signals, Signals in Components and linkedSignal and resource.

Dependency injection

TypeScript
import { Injectable, InjectionToken, inject } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class Cart {
  private items = signal<string[]>([]);
  readonly count = computed(() => this.items().length);
  add(name: string): void {
    this.items.update((list) => [...list, name]);
  }
}

export const API_URL = new InjectionToken<string>('API_URL', {
  factory: () => '/api',
});

// In a component, function guard or interceptor:
const cart = inject(Cart);
const url = inject(API_URL);
const maybe = inject(Logger, { optional: true });
TypeScript
// app.config.ts
export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes, withComponentInputBinding()),
    provideHttpClient(withFetch(), withInterceptors([authInterceptor])),
    { provide: API_URL, useValue: 'https://example.com/api' },
    { provide: Logger, useClass: ConsoleLogger },
    { provide: Config, useFactory: () => buildConfig(inject(API_URL)) },
    { provide: OldName, useExisting: NewName },
  ],
};

A component's providers: [...] gives each instance its own copy. See Services and DI and Providers, InjectionToken and Scopes.

Routing

TypeScript
export const routes: Routes = [
  { path: '', component: Home, title: 'Home' },
  { path: 'users/:id', component: UserDetail, resolve: { user: userResolver } },
  { path: 'admin', canMatch: [adminGuard], loadChildren: () => import('./admin/routes').then((m) => m.ADMIN_ROUTES) },
  { path: 'about', loadComponent: () => import('./about').then((m) => m.About) },
  { path: 'old', redirectTo: '', pathMatch: 'full' },
  { path: '**', component: NotFound },
];

export const adminGuard: CanMatchFn = () => {
  const auth = inject(Auth);
  return auth.isAdmin() ? true : inject(Router).parseUrl('/login');
};
HTML
<a routerLink="/users/42" routerLinkActive="active" [queryParams]="{ tab: 'info' }">User</a>
<router-outlet />
TypeScript
router.navigate(['/users', id], { queryParams: { tab: 'info' } });
// with withComponentInputBinding(): path/query params arrive as inputs
id = input.required<string>();

See Routing Basics, Route Parameters, Lazy Loading and Guards and Resolvers.

Forms

TypeScript
// Reactive
private fb = inject(NonNullableFormBuilder);
form = this.fb.group({
  email: ['', [Validators.required, Validators.email]],
  password: ['', [Validators.required, Validators.minLength(8)]],
  tags: this.fb.array<string>([]),
});

submit(): void {
  if (this.form.invalid) {
    return;
  }
  console.log(this.form.getRawValue());
}
HTML
<form [formGroup]="form" (ngSubmit)="submit()">
  <input type="email" formControlName="email" />
  @if (form.controls.email.touched && form.controls.email.hasError('required')) {
    <p role="alert">Email is required.</p>
  }
  <button type="submit" [disabled]="form.invalid">Sign in</button>
</form>
TypeScript
// Custom validator: null means valid
const noSpaces: ValidatorFn = (control) =>
  /\s/.test(control.value ?? '') ? { noSpaces: true } : null;

Template-driven forms use FormsModule with ngModel and #f="ngForm". Signal forms are a newer, evolving API: check the docs. See Template-Driven Forms, Reactive Forms, Validation and Signal Forms.

HttpClient

TypeScript
private http = inject(HttpClient);

getUsers(): Observable<User[]> {
  return this.http.get<User[]>('/api/users', { params: { page: 1 } });
}
createUser(user: NewUser): Observable<User> {
  return this.http.post<User>('/api/users', user);
}

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const token = inject(Auth).token();
  return next(token ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req);
};

Register with provideHttpClient(withFetch(), withInterceptors([authInterceptor])). Calls are lazy: nothing is sent until you subscribe (or use async, toSignal, httpResource). See HttpClient and Interceptors.

RxJS operators

Operator Use it for
map, filter, tap Transform, drop, side-effect
switchMap Cancel the previous inner request (search)
mergeMap Run inner observables in parallel
concatMap Queue inner observables in order
exhaustMap Ignore new values while busy (submit)
debounceTime(300), distinctUntilChanged() Calm down fast input
combineLatest([a$, b$]) Latest value of several streams
catchError(() => of([])) Recover from an error
retry(2) Resubscribe on error
takeUntilDestroyed() End a stream when the component is destroyed
shareReplay(1) Share one subscription and replay the last value
TypeScript
results = toSignal(
  this.query$.pipe(
    debounceTime(300),
    distinctUntilChanged(),
    switchMap((q) => this.api.search(q).pipe(catchError(() => of([])))),
  ),
  { initialValue: [] },
);

See RxJS Essentials, RxJS Operators and Signals and RxJS Interop. The first stand-in below models the shape of a pipe chain.

TypeScript Stand-in: a pipe of operators over a synchronous stream

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

This model works on arrays, one step at a time. Real observables are lazy and push values over time, so debounceTime and switchMap have no array equivalent.

Testing snippets

TypeScript
// Component
beforeEach(() => TestBed.configureTestingModule({ imports: [Counter] }));

it('increments', () => {
  const fixture = TestBed.createComponent(Counter);
  fixture.componentRef.setInput('start', 0);
  fixture.detectChanges();
  fixture.nativeElement.querySelector('button').click();
  fixture.detectChanges();
  expect(fixture.nativeElement.textContent).toContain('1');
});

// Service with a fake HTTP backend
TestBed.configureTestingModule({
  providers: [provideHttpClient(), provideHttpClientTesting()],
});
const controller = TestBed.inject(HttpTestingController);
service.getUsers().subscribe();
controller.expectOne('/api/users?page=1').flush([]);
controller.verify();

// Replace a dependency
TestBed.configureTestingModule({ providers: [{ provide: Auth, useValue: fakeAuth }] });

Testing a pure function needs no TestBed at all. See Testing Components and Services.

Lifecycle order

flowchart LR
  A["constructor"] --> B["ngOnChanges"] --> C["ngOnInit"] --> D["ngDoCheck"] --> E["ngAfterContentInit"] --> F["ngAfterViewInit"] --> G["ngOnDestroy"]

Each hook runs once, except ngOnChanges and ngDoCheck, which repeat. ngAfterContentChecked and ngAfterViewChecked also repeat. Use DestroyRef for cleanup next to the code that needs it.

See Lifecycle Hooks. The second stand-in shows how a route table with :param segments and a wildcard picks a match.

TypeScript Stand-in: matching paths against a route table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The real router also handles redirects, pathMatch, children, outlets and more. The order of the table matters: the first match wins, so put ** last.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which template line toggles a single CSS class?

    [class.name]="condition" adds or removes exactly one class. The other forms are not valid bindings for that.
  2. 2. What does @for require that *ngFor did not?

    @for (item of items; track item.id) must say how to identify items, so Angular can reuse DOM nodes. It also needs no imports.
  3. 3. How do you provide a different implementation for an abstract class in tests or at runtime?

    A provider object maps a token (provide) to a class (useClass), value (useValue), factory (useFactory) or alias (useExisting).
  4. 4. In which order do HTTP interceptors registered as withInterceptors([a, b]) see a response?

    The request goes through the chain in array order and the response comes back through it in reverse.

Summary

  • Components are standalone classes with a template; inputs and outputs are functions (input(), output(), model()).
  • Templates use {{ }}, [prop], (event), [(two-way)], and the built-in @if, @for (with track), @switch and @defer blocks.
  • State is a signal, derived values are computed, side effects are effect; replace objects instead of mutating them.
  • Services are provided with providedIn: 'root' or providers and used with inject(); tokens and provider objects swap implementations.
  • Routes are plain data (loadComponent, guards, resolvers); forms are reactive or template-driven; HTTP and RxJS handle streams over time.
  • Test with TestBed, fakes through providers and HttpTestingController.

Next: start again from What Is Angular?, or work through the Practice Exercises.