Angular Cheat Sheet

Last Updated: November 21, 2025

Component Structure

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

@Component({
  selector: 'app-hello',
  template: `
    <h1>{{ title }}</h1>
    <p>{{ message }}</p>
  `,
  styleUrls: ['./hello.component.css']
})
export class HelloComponent {
  title = 'Hello Angular';
  message = 'Welcome!';

  onClick() {
    console.log('Clicked!');
  }
}

Template Syntax

<!-- Interpolation -->
<p>{{ message }}</p>

<!-- Property Binding -->
<img [src]="imageUrl" [alt]="imageAlt">

<!-- Event Binding -->
<button (click)="onClick()">Click</button>

<!-- Two-way Binding -->
<input [(ngModel)]="name">

<!-- Structural Directives -->
<div *ngIf="isVisible">Visible</div>
<div *ngFor="let item of items">{{ item }}</div>

<!-- Class & Style Binding -->
<div [class.active]="isActive"></div>
<div [style.color]="textColor"></div>

Services & Dependency Injection

// data.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  constructor(private http: HttpClient) {}

  getData() {
    return this.http.get('https://api.example.com/data');
  }
}

// Using in component
export class MyComponent {
  constructor(private dataService: DataService) {}

  ngOnInit() {
    this.dataService.getData().subscribe(data => {
      console.log(data);
    });
  }
}

Lifecycle Hooks

Hook Purpose
ngOnInit Initialize component
ngOnChanges When input properties change
ngOnDestroy Cleanup before destruction
ngAfterViewInit After view initialization
ngDoCheck Custom change detection

Common Directives

Directive Description
*ngIf Conditional rendering
*ngFor Loop over items
*ngSwitch Switch case rendering
[ngClass] Dynamic classes
[ngStyle] Dynamic styles
[(ngModel)] Two-way data binding
💡 Pro Tip: Use OnPush change detection strategy for better performance!
← Back to Programming Languages | Browse all categories | View all cheat sheets