Skip to main content
Quick Reference

Angular Cheatsheet

Modern Angular on one page — standalone components, template bindings, built-in control flow, signals, services, HttpClient, routing, reactive forms, and the traps that show up in interviews.

10 sections 10 tables 16 code snippets

CLI & a new app

Start and generate

ng new shop
ng serve
ng generate component user-card
ng generate service users
ng build

Where configuration lives

src/main.ts            bootstrap
src/app/app.config.ts   providers
src/app/app.routes.ts   routes
src/app/app.ts          root component

What a new app uses

PieceRole
ng serveDev server, usually http://localhost:4200
Standalone componentsThe default since Angular 19. No NgModule for new code
app.config.tsRegisters the router, HttpClient, and other app-wide providers
templateUrlThe HTML file for one component
SignalsThe current way to hold component state

NgModules still work. New components should stay standalone. A module is the old way to group declarations and imports.

A standalone component

The class

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

@Component({
  selector: 'app-user-card',
  templateUrl: './user-card.component.html',
  styleUrl: './user-card.component.css',
})
export class UserCardComponent {}

Decorator fields

FieldMeaning
selectorThe tag you write in a parent template: <app-user-card>
templateUrlExternal HTML. template is the inline alternative
styleUrlOne stylesheet. styleUrls is the array form
importsOther standalone components, directives, and pipes this template uses
standaloneDefaults to true on Angular 19 and later. Omit it

Template bindings

Text, property, event

<p>{{ name() }}</p>
<img [src]="photo()" [alt]="name()" />
<button (click)="save()">Save</button>
<input [value]="query()" (input)="onInput($event)" />

Which brackets

FormDirection
{{ name() }}Class to text. Read a signal with ()
[src]="photo()"Class to a DOM property
(click)="save()"DOM event to a method
[class.active]="on()"Toggle a class when the expression is true
[style.color]="tone()"Set one CSS property
[(ngModel)]="name"Two-way. Needs FormsModule. Prefer a signal model() or a reactive form

Square brackets set a property. Parentheses listen. Writing src="{{ photo() }}" stringifies the value. Prefer [src]="photo()" for anything that is not plain text.

Built-in control flow

@if and @for

@if (user(); as current) {
  <p>Hello, {{ current.name }}</p>
} @else {
  <p>Sign in</p>
}

@for (item of items(); track item.id) {
  <li>{{ item.name }}</li>
} @empty {
  <li>Nothing yet</li>
}

Blocks

BlockUse
@if / @else if / @elseShow one branch. The other branch is not in the DOM
@if (expr; as name)Test and give the truthy value a name
@forRepeat. track is required
@emptyRendered when the @for collection is empty
@switch / @case / @defaultPick one branch from a value. No fall-through
@deferLoad a heavy standalone component later, for example on viewport

These blocks need no import. *ngIf and *ngFor still work if you import them, but new templates should use @if and @for.

Signals

Local state

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

inc() {
  this.count.update((n) => n + 1);
}

Read it in the template

<button (click)="inc()">{{ count() }}</button>
<p>{{ doubled() }}</p>

Signal APIs

APIRole
signal(0)Writable state. () reads, set replaces, update derives the next value
computed(...)Read-only value that recomputes when its signals change
effect(...)A side effect. Create it in the constructor or a field, not in a click handler
input() / input.required()A signal input from the parent
output()Emits to the parent. Call emit
model()A two-way signal input

Replace state. items().push(row) mutates the array and does not notify readers. update with a new array.

Services & inject()

An app-wide service

import { inject, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({ providedIn: 'root' })
export class UsersService {
  private http = inject(HttpClient);

  list() {
    return this.http.get<User[]>('/api/users');
  }
}

Who creates it

ProviderLifetime
providedIn: "root"One instance for the whole app
providers on a componentA new instance for that component and its children
providers in app.config.tsApp-wide, when the class has no providedIn
inject(Token)Read a dependency. Only legal in an injection context

Call inject() in a field or constructor, not inside save(). The click handler is not an injection context, so a late inject() throws.

HttpClient

Register it once

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

Read it as a signal

private usersService = inject(UsersService);

users = toSignal(this.usersService.list(), {
  initialValue: [],
});

Calls

MethodTypical use
get<T>(url)Read a list or one resource
post<T>(url, body)Create
put / patchReplace or partially update
deleteRemove
toSignal(obs)Subscribe for the template. Pass initialValue when there is no current value yet

provideHttpClient() comes from @angular/common/http. toSignal comes from @angular/core/rxjs-interop. Without the provider, inject(HttpClient) fails at runtime.

Routing

Routes

export const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'users/:id', component: UserComponent },
];

Links and the outlet

<a routerLink="/users/1" routerLinkActive="active">
  User
</a>
<router-outlet />

Routing pieces

PieceRole
provideRouter(routes)Turns the route table on. Add it in app.config.ts
routerLink="/users/1"Absolute link. Without the leading slash it is relative to the current URL
routerLinkActiveAdds a CSS class when the link matches
<router-outlet>Where the matched component is inserted
withComponentInputBinding()Passes the :id param into an input() of the same name
RouterLink, RouterOutletImport both in the component imports array or the template ignores them

Reactive forms

The model

form = new FormGroup({
  email: new FormControl('', {
    nonNullable: true,
    validators: [Validators.required, Validators.email],
  }),
});

submit() {
  if (this.form.invalid) return;
  console.log(this.form.getRawValue());
}

The template

<form [formGroup]="form" (ngSubmit)="submit()">
  <input formControlName="email" />
  <button type="submit">Save</button>
</form>

Wire-up

ImportWhy
ReactiveFormsModuleAdd it to the component imports array
FormGroupA set of controls, checked together
FormControlOne field. nonNullable: true keeps the value a string
formControlNameMust match the key in the group
getRawValue()Includes disabled controls. .value omits them

Do not put ngModel on a control that already has formControlName. Pick reactive forms for anything you will validate.

Interview traps

Traps worth memorising

TrapWhat happensPrefer
{{ count }} for a signalPrints the signal object, not the number{{ count() }}
items().push(row)The view does not updateupdate with a new array
track $indexDOM nodes stick to the slot when the list is reorderedtrack item.id
inject() inside save()Runtime error: no injection contextA field initializer
No provideHttpClient()inject(HttpClient) failsAdd it next to provideRouter
.subscribe() and leave itThe request outlives the componenttoSignal, the async pipe, or takeUntilDestroyed()
routerLink not importedThe anchor does not navigateImport RouterLink on that component
routerLink="users"Relative to the current URLrouterLink="/users" when you mean the root
*ngIf in a new templateUnknown unless NgIf is imported@if
[(ngModel)] with no FormsModuleThe binding is unknownReactive forms, or import FormsModule
Mutating a property under OnPushThe view can stay staleReplace the object, or store it in a signal
effect() that writes a signal it readsExtra runs, sometimes a loopcomputed() for derived state

Replace the list

add(row: Item) {
  this.items.update((list) => [...list, row]);
}

Track a stable id

@for (item of items(); track item.id) {
  <app-row [item]="item" />
}

How to use this page: generate a component, give it a signal, and render it with {{ count() }}. Then add @for with track item.id and delete the track clause so the compiler shows you it is required.