Angular Cheat Sheet

Valid for Angular 22. The blue labels show the Angular version in which a feature was introduced, red labels mark deprecated APIs.

Defaults of a new Angular 22 project

What Since Consequence
standalone components, directives and pipes 19 standalone: true is the default and no longer needs to be written. Everything used in a template must be listed in imports.
new style guide: no Component suffix 20 ng generate component app creates app.ts, app.html, app.css with the class App.
zoneless change detection 21 Zone.js is no longer included. The view is updated by signals, template events, the async pipe or markForCheck().
ChangeDetectionStrategy.OnPush 22 OnPush is the default. The old behaviour is called ChangeDetectionStrategy.Eager (Default is deprecated). Prefer signals for state.
Fetch API in HttpClient 22 withFetch() is deprecated, use withXhr() to get the old XMLHttpRequest backend.

Signals

What How
Definition
Angular 16
import { signal, WritableSignal } from '@angular/core';

@Component({
...
})
export class App {
  mySignal : WritableSignal<string> = signal('Hello World !');
}
                        
reading
mySignal()
setting a new value
mySignal.set('Have a nice day')
update based on the current value
mySignal.update(value => value + ' !')
read-only view
readonlySignal : Signal<string> = mySignal.asReadonly();
computed signal
count : WritableSignal<number> = signal(0);
doubleCount : Signal<number> = computed(() => this.count() * 2);
                        
linkedSignal: writable signal that is reset when its source changes
Angular 19
options = signal(['Apple', 'Banana', 'Cherry']);
selected : WritableSignal<string> = linkedSignal(() => this.options()[0]);
                        
effect
only in an injection context (field initializer or constructor)
constructor() {
  effect(() => {
    console.log(`The current count is: ${this.count()}`);
  });
}
                        
resource: asynchronous data as signals
Angular 19 (stable since 22)
bookId = signal(1);

book = resource({
  params: () => ({ id: this.bookId() }),
  loader: ({ params }) => fetch(`/api/books/${params.id}`).then(response => response.json())
});

// book.value(), book.isLoading(), book.error(), book.hasValue(), book.reload()
                        
Observable ↔ Signal (RxJS interop)
import { toSignal, toObservable } from '@angular/core/rxjs-interop';

counter : Signal<number | undefined> = toSignal(interval(1000));
count$ : Observable<number> = toObservable(this.count);
                        

inside a component

Use case Template content of component Angular code of component
display string value from @let
Angular 18.1
@let message = 'Hello World !';
{{ message }}
                        
display string value from component {{ message }}
@Component({
...
})
export class App {
  // default visibility is public, protected is enough for the template
  message : string = 'Hello World !';
}
                        
display string value from a signal in a component
Angular 16
{{ message() }}
@Component({
...
})
export class App {
  message : WritableSignal<string> = signal('Hello World !');
}
                        
property binding on HTML tags <button [disabled]="!isFormValid()">Save</button>
@Component({
  selector: 'app-root',
...
})
export class App {
  isFormValid = signal(true);
}
                        
class and style binding
<div [class.active]="isActive()">...</div>
<div [class]="{ active: isActive(), disabled: false }">...</div>
<div [style.width.px]="width()">...</div>
                        
export class App {
  isActive = signal(true);
  width = signal(200);
}
                        
prefer these over ngClass / ngStyle
pipe usage {{ message | uppercase }}
import { UpperCasePipe } from '@angular/common';

@Component({
  selector: 'app-root',
  imports: [UpperCasePipe],
...
})
export class App {
  message : string = 'Hello World !';
}
                        
if, else, else-if
Angular 17
@if (a > b) {
  {{ a }} is greater than {{ b }}
} @else if (b > a) {
  {{ a }} is less than {{ b }}
} @else {
  {{ a }} is equal to {{ b }}
}

<!-- store the result in a variable -->
@if (user(); as u) {
  {{ u.name }}
}
                        
@Component({
  selector: 'app-root',
...
})
export class App {
  a : number = 5;
  b : number = 6;
  user = signal<User | undefined>(undefined);
}
                        
if, else as structural directive (classic)
deprecated since Angular 20
<div *ngIf="a > b; else notGreater">
  {{ a }} is greater than {{ b }}
</div>
<ng-template #notGreater>
  {{ a }} is not greater than {{ b }}
</ng-template>
                        
there is no else-if, use several *ngIf
import { NgIf } from '@angular/common';

@Component({
  selector: 'app-root',
  imports: [NgIf],
...
})
export class App {
  a : number = 5;
  b : number = 6;
}
                        
switch
Angular 17
@switch (europeanCountry) {
  @case ('Switzerland') {
    <div>CHF</div>
  }
  @case ('Germany') {
    <div>EUR</div>
  }
  @case ('Sweden') {
    <div>SEK</div>
  }
  @default {
    <div>EUR</div>
  }
}
                        
@Component({
  selector: 'app-root',
...
})
export class App {
  europeanCountry : string = 'Switzerland';
}
                        
switch as structural directive (classic)
deprecated since Angular 20
<div [ngSwitch]="europeanCountry">
  <div *ngSwitchCase="'Switzerland'">
    CHF
  </div>
  <div *ngSwitchCase="'Germany'">
    EUR
  </div>
  <div *ngSwitchCase="'Sweden'">
    SEK
  </div>
  <div *ngSwitchDefault>
    EUR
  </div>
</div>
                        
import { NgSwitch, NgSwitchCase, NgSwitchDefault } from '@angular/common';

@Component({
  selector: 'app-root',
  imports: [NgSwitch, NgSwitchCase, NgSwitchDefault],
...
})
export class App {
  europeanCountry : string = 'Switzerland';
}
                        
for-loop
Angular 17
<ul>
  @for (item of items; track item; let i = $index) {
    <li>{{ i }}: {{ item }}</li>
  } @empty {
    <li>no items</li>
  }
</ul>
                        
track is mandatory; for objects use an id, e.g. track item.id. Further variables: $count, $first, $last, $even, $odd
@Component({
  selector: 'app-root',
...
})
export class App {
  items = ['Apple', 'Banana', 'Cherry'];
}
                        
for-loop as structural directive (classic)
deprecated since Angular 20
<ul>
  <li *ngFor="let item of items; let i = index; trackBy: trackByFn">{{ i }}: {{ item }}</li>
</ul>
                        
import { NgFor } from '@angular/common';

@Component({
  selector: 'app-root',
  imports: [NgFor],
...
})
export class App {
  items = ['Apple', 'Banana', 'Cherry'];

  trackByFn(index : number, item : string) : string {
    return item;
  }
}
                        
lazy loading of a template part with @defer
Angular 17
@defer (on viewport) {
  <large-chart />
} @placeholder {
  <p>Chart will be loaded</p>
} @loading (minimum 500ms) {
  <p>Loading ...</p>
} @error {
  <p>Loading failed</p>
}
                        
other triggers: on idle, on immediate, on timer(2s), on interaction, on hover, when condition
@Component({
  selector: 'app-root',
  imports: [LargeChart],
...
})
export class App {}
                        
the deferred component must be standalone and not be used elsewhere in the class
grouping without an extra DOM element
<ng-container>
  <li>first</li>
  <li>second</li>
</ng-container>
                        
reusable template with ng-template and NgTemplateOutlet
<ng-template #greeting let-name>
  Hello {{ name }} !
</ng-template>

<ng-container *ngTemplateOutlet="greeting; context: { $implicit: 'World' }" />
                        
import { NgTemplateOutlet } from '@angular/common';

@Component({
  selector: 'app-root',
  imports: [NgTemplateOutlet],
...
})
export class App {}
                        
event binding in an HTML element
<button (click)="doSomething()">Click me!</button>
                        
@Component({
  selector: 'app-root',
...
})
export class App {
  doSomething() : void {
    // here we do something
  }
}
                        
event binding in an HTML element with passing $event
<button (click)="doSomething($event)">Click me!</button>
<input (keyup.enter)="search()">
                        
@Component({
  selector: 'app-root',
...
})
export class App {
  doSomething(event : MouseEvent) : void {
    // here we do something
  }

  search() : void {
    // here we do something
  }
}
                        
two-way binding with HTML tags (template-driven forms)
<div>
  <input type="number" [(ngModel)]="firstNumber">
</div>
<div>
  <input type="number" [(ngModel)]="secondNumber">
</div>
<div>
  <button (click)="sum()">Add</button>
</div>
                        
@Component({
  selector: 'app-root',
  imports: [FormsModule],
  ...
})
export class App {
  // signals work with [(ngModel)] too
  firstNumber = signal(0);
  secondNumber = signal(0);

  sum() : void {
    console.log(this.firstNumber() + this.secondNumber());
  }
}
                        
Signal Forms
Angular 21 (stable since 22)
<input type="email" [formField]="loginForm.email">
@if (loginForm.email().invalid() && loginForm.email().touched()) {
  @for (error of loginForm.email().errors(); track error) {
    <p>{{ error.message }}</p>
  }
}
<input type="password" [formField]="loginForm.password">
<button [disabled]="loginForm().invalid()" (click)="login()">Login</button>
                        
import { form, FormField, required, email } from '@angular/forms/signals';

@Component({
  selector: 'app-root',
  imports: [FormField],
  ...
})
export class App {
  loginModel = signal({ email: '', password: '' });

  loginForm = form(this.loginModel, (path) => {
    required(path.email, { message: 'E-Mail is required' });
    email(path.email, { message: 'E-Mail is invalid' });
    required(path.password);
  });

  login() : void {
    console.log(this.loginModel());
  }
}
                        

component interactions

Use case Template content of consumer Template content of component Angular code of consumer Angular code of component
tag <app-root></app-root>
or self-closing: <app-root />
// app.ts
@Component({
  selector: 'app-root',
  imports: [],
  templateUrl: './app.html',
  styleUrl: './app.css'
})
export class App {
}
                        
standalone: true and changeDetection: ChangeDetectionStrategy.OnPush are defaults
input parameters (classic)
<!-- static string -->
<echo message="Hello World !"/>
<!-- expression -->
<echo [message]="greeting"/>
                        
{{ message }} not required
@Component({
  selector: 'echo',
...
})
export class Echo {
  @Input() message : string = '';
}
                        
required
@Component({
  selector: 'echo',
...
})
export class Echo {
  @Input({ required: true }) message! : string;
}
                        
input parameters (signal input)
Angular 17.1
<!-- static string -->
<echo message="Hello World !"/>
<!-- expression -->
<echo [message]="greeting"/>
                        
{{ message() }} not required
@Component({
  selector: 'echo',
...
})
export class Echo {
  readonly message : InputSignal<string | undefined> = input<string>();
  // with default value
  readonly title : InputSignal<string> = input('Hello');
}
                        
required
@Component({
  selector: 'echo',
...
})
export class Echo {
  readonly message : InputSignal<string> = input.required<string>();
}
                        
two-way binding with custom tags (classic)
<custom-slider [(value)]="volume"/>
                        
@Component({
  selector: 'app-root',
  imports: [CustomSlider],
...
})
export class App {
  volume : number = 50;
}
                        
@Component({
  selector: 'custom-slider',
...
})
export class CustomSlider {
  @Input() value : number = 0;
  @Output() valueChange = new EventEmitter<number>();
}
                        
the output must be named input name + Change
two-way binding with custom tags and model()
Angular 17.2
<custom-slider [(value)]="volume"/>
                        
@Component({
  selector: 'app-root',
  imports: [CustomSlider],
...
})
export class App {
  volume = signal(50); // a plain field works too
}
                        
@Component({
  selector: 'custom-slider',
...
})
export class CustomSlider {
  value : ModelSignal<number> = model(0);

  increment() : void {
    this.value.update(v => v + 1); // propagated to the consumer
  }
}
                        
output: event firing on a component (classic) <alarm-demo (myAlarm)="onAlarm($event)"></alarm-demo>
@Component({
  selector: 'app-root',
  imports: [AlarmDemo],
  ...
})
export class App {
  onAlarm(alarm : Alarm) : void {
    // here we do something
  }
}
                        
@Component({
  selector: 'alarm-demo',
...
})
export class AlarmDemo {
  @Output() myAlarm : EventEmitter<Alarm> = new EventEmitter<Alarm>();

  raise() : void {
    this.myAlarm.emit({ level: 'high' });
  }
}
                        
output: event firing on a component with output()
Angular 17.3
<alarm-demo (myAlarm)="onAlarm($event)"></alarm-demo>
@Component({
  selector: 'app-root',
  imports: [AlarmDemo],
  ...
})
export class App {
  onAlarm(alarm : Alarm) : void {
    // here we do something
  }
}
                        
@Component({
  selector: 'alarm-demo',
...
})
export class AlarmDemo {
  myAlarm : OutputEmitterRef<Alarm> = output<Alarm>();

  raise() : void {
    this.myAlarm.emit({ level: 'high' });
  }
}
                        
output() is not a signal, it has no value
view queries: access a child element or component
Angular 17.2
<input #nameInput>
<custom-slider />
                        
export class App {
  nameInput : Signal<ElementRef | undefined> = viewChild<ElementRef>('nameInput');
  slider : Signal<CustomSlider> = viewChild.required(CustomSlider);
}
                        
classic: @ViewChild('nameInput') nameInput!: ElementRef;. Also: viewChildren(), contentChild(), contentChildren()
dependency injection: by constructor (classic)
provision: global
@Component({
  selector: 'app-root',
...
})
export class App {
  constructor(private service: RandomNumberService) {}
}
                        
@Injectable({
  providedIn: 'root'
})
export class RandomNumberService {

  randomNumber() : number {
    return Math.floor(Math.random() * 100);
  }
}
                        
dependency injection: by inject()
Angular 14
provision: global
@Component({
  selector: 'app-root',
...
})
export class App {
  private service : RandomNumberService = inject(RandomNumberService);
}
                        
@Injectable({
  providedIn: 'root'
})
export class RandomNumberService {

  randomNumber() : number {
    return Math.floor(Math.random() * 100);
  }
}
                        
dependency injection: with @Service
Angular 22
provision: global
@Component({
  selector: 'app-root',
...
})
export class App {
  private service : RandomNumberService = inject(RandomNumberService);
}
                        
@Service() // = @Injectable({ providedIn: 'root' })
export class RandomNumberService {

  randomNumber() : number {
    return Math.floor(Math.random() * 100);
  }
}
                        
dependencies of a @Service must be obtained with inject(), not by constructor
HttpClient with NgModule (classic)
HttpClientModule deprecated since Angular 18
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { BrowserModule } from '@angular/platform-browser';

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
                        
@Injectable({
  providedIn: 'root'
})
export class BookStoreService {
  private apiUrl = 'https://api5.angular-buch.com';

  constructor(private http: HttpClient) {}

  getAll(): Observable<Book[]> {
    return this.http.get<Book[]>(`${this.apiUrl}/books`);
  }
}
                        
HttpClient with provideHttpClient()
Angular 15
// app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient } from '@angular/common/http';

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

// main.ts
bootstrapApplication(App, appConfig);
                        
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';

import { Book } from './book';

@Injectable({
  providedIn: 'root'
})
export class BookStoreService {
  private apiUrl = 'https://api5.angular-buch.com';
  private http = inject(HttpClient);

  getAll(): Observable<Book[]> {
    return this.http.get<Book[]>(`${this.apiUrl}/books`);
  }

  getSingle(isbn: string): Observable<Book> {
    return this.http.get<Book>(`${this.apiUrl}/books/${isbn}`);
  }

  remove(isbn: string): Observable<unknown> {
    return this.http.delete(`${this.apiUrl}/books/${isbn}`);
  }
}
                        
httpResource(): HTTP request as signal
Angular 19.2 (stable since 22)
@if (book.isLoading()) {
  Loading ...
} @else if (book.hasValue()) {
  {{ book.value().title }}
}
                        
import { httpResource } from '@angular/common/http';

export class BookDetails {
  isbn = input.required<string>();

  // reloads automatically when isbn() changes
  book = httpResource<Book>(() => `https://api5.angular-buch.com/books/${this.isbn()}`);
}
                        
intended for reading data, use HttpClient for mutations
content projection with ng-content
tutorial
<custom-card>
  Hello World !
</custom-card>
                        
<div>
  <ng-content />
</div>
                        
@Component({
  selector: 'custom-card',
...
})
export class CustomCard {}
                        
content projection with several slots
<custom-card>
  <h3 card-title>Title</h3>
  Hello World !
</custom-card>
                        
<div>
  <ng-content select="[card-title]" />
  <ng-content /> <!-- the rest -->
</div>
                        
attribute directive
<p makeMeYellow>Hello World!</p>
                        
@Component({
  selector: 'app-root',
  imports: [MakeMeYellow],
...
})
export class App {}
                        
import { Directive, ElementRef, inject } from '@angular/core';

@Directive({
  selector: '[makeMeYellow]',
})
export class MakeMeYellow {
  private el = inject(ElementRef);

  constructor() {
    this.el.nativeElement.style.backgroundColor = 'yellow';
  }
}
                        
structural directive
<p *showIf="isHighlighted">This text appears only if `isHighlighted` is true!</p>
                        
import { Directive, Input, TemplateRef, ViewContainerRef, inject } from '@angular/core';

@Directive({
  selector: '[showIf]'
})
export class ShowIf {
  private templateRef = inject(TemplateRef<unknown>);
  private viewContainer = inject(ViewContainerRef);

  @Input() set showIf(condition: boolean) {
    this.viewContainer.clear();
    if (condition) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    }
  }
}
                        
attribute directive with host property (recommended)
<p appHighlight>Highlight me!</p>
                        
import { Directive, signal } from '@angular/core';

@Directive({
  selector: '[appHighlight]',
  host: {
    '(mouseenter)': 'color.set("yellow")',
    '(mouseleave)': 'color.set("")',
    '[style.backgroundColor]': 'color()'
  }
})
export class Highlight {
  protected color = signal('');
}
                        
attribute directive with @HostListener (classic)
<p appHighlight>Highlight me!</p>
                        
import { Directive, ElementRef, HostListener, inject } from '@angular/core';

@Directive({
  selector: '[appHighlight]',
})
export class Highlight {
  private el = inject(ElementRef);

  @HostListener('mouseenter') onMouseEnter() {
    this.highlight('yellow');
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.highlight('');
  }

  private highlight(color: string) {
    this.el.nativeElement.style.backgroundColor = color;
  }
}
                        
attribute directive with @HostBinding and @HostListener (classic, to convert to lower case letters)
<label>E-Mail: </label>
<input type="text" chLowerCase/>
                        
@Directive({selector: '[chLowerCase]'})
export class LowerCase {

  @HostBinding('value') value = '';

  @HostListener('change', ['$event']) onChange(event: Event) {
    this.value = (event.target as HTMLInputElement).value.toLowerCase();
  }
}
                        
with the host property: host: { '[value]': 'value()', '(change)': 'onChange($event)' }
Pipe
<p>{{ 'Angular' | reverse }}</p>
                        
@Component({
  selector: 'app-root',
  imports: [ReversePipe],
...
})
export class App {}
                        
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'reverse'  // name of the pipe in templates
})
export class ReversePipe implements PipeTransform {
  transform(value: string): string {
    return value.split('').reverse().join('');
  }
}
                        
Pipe with a parameter
<p>{{ 'Hello ' | repeat:3 }}</p>   <!-- Output: Hello Hello Hello -->
<p>{{ 'Angular ' | repeat:2 }}</p> <!-- Output: Angular Angular -->
                        
@Component({
  selector: 'app-root',
  imports: [RepeatPipe],
...
})
export class App {}
                        
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'repeat'
})
export class RepeatPipe implements PipeTransform {
  transform(value: string, times: number = 1): string {
    return value.repeat(times);
  }
}
                        

routing

Use case code
standalone routing
Angular 15
// app.routes.ts
import { Routes } from '@angular/router';
import { Home } from './home/home';

export const routes : Routes = [
  { path: '', component: Home },
  { path: 'about', loadComponent: () => import('./about/about').then(m => m.About) }, // lazy loaded
  { path: 'books/:isbn', component: BookDetails },
  { path: '**', redirectTo: '' }
];

// app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { routes } from './app.routes';

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

// main.ts
import { bootstrapApplication } from '@angular/platform-browser';
import { App } from './app/app';
import { appConfig } from './app/app.config';

bootstrapApplication(App, appConfig);
                        
withComponentInputBinding() binds the route parameter :isbn to isbn = input.required<string>() of BookDetails
outlet and links
<nav>
  <a routerLink="/" routerLinkActive="active">Home</a>
  <a routerLink="/about" routerLinkActive="active">About</a>
  <a [routerLink]="['/books', isbn]">Book</a>
</nav>
<router-outlet />

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

// navigation in code
private router = inject(Router);
this.router.navigate(['/books', isbn]);
                        
NgModule routing (classic)
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';

const routes : Routes = [
  { path: '', component: HomeComponent },
  { path: 'about', component: AboutComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }