Introduction

Angular is a popular front-end web framework developed by Google. It helps you build fast, interactive, and structured single-page applications (SPAs) using HTML, CSS, and TypeScript. Angular provides tools like components, services, routing, and dependency injection that make building large-scale web apps easier and more organized.

1. Angular Module (NgModule)

Definition: A module is a container for components, services, directives, and pipes. Every Angular app has at least one root module called AppModule.

Example

JavaScript
@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  bootstrap: [AppComponent]
})
export class AppModule { }

Key Point: Modules organize the app into functional sections.

2. Component

Definition: A component controls a part of the user interface. Each component has three parts: HTML template, TypeScript class, and CSS style.

Example

JavaScript
@Component({
  selector: 'app-hello',
  template: '<h1>Hello {{ name }}</h1>'
})
export class HelloComponent {
  name = 'World';
}

Key Point: Components are the basic building blocks of any Angular app.

3. Data Binding

Definition: Data binding connects the data between your class (TypeScript) and the template (HTML).

Types and Examples

  • Interpolation: {{ value }}
  • Property Binding: [src]="imageUrl"
  • Event Binding: (click)="doSomething()"
  • Two-way Binding: [(ngModel)]="name"

Key Point: Use FormsModule for two-way binding with ngModel.

4. Directives

Definition: Directives change the behavior or appearance of elements.

Types

  • Structural Directives: *ngIf, *ngFor
  • Attribute Directives: [ngClass], [ngStyle]

Example

JavaScript
<p *ngIf="isVisible">This is visible</p>

Key Point: Structural directives change the DOM layout.

5. Services and Dependency Injection

Definition: Services are used to share data or logic across components. Angular uses dependency injection to provide services.

Example

JavaScript
@Injectable()
export class DataService {
  getData() {
    return ['One', 'Two', 'Three'];
  }
}

Key Point: Use services to avoid repeating logic in multiple components.

6. Routing

Definition: Routing is used to navigate between different views or components.

Example

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

Key Point: Use <router-outlet> in HTML to display routed views.

7. Lifecycle Hooks

Definition: Hooks let you run code at specific times in a component’s life.

Common Hooks

  • ngOnInit(): Runs after component initializes.
  • ngOnDestroy(): Runs before component is removed.

Example

JavaScript
ngOnInit() {
  console.log('Component loaded');
}

Key Point: Use ngOnInit() to fetch data when the component loads.

8. Pipes

Definition: Pipes transform the data in the template.

Built-in Pipes: date, uppercase, lowercase, currency

Example

JavaScript
<p>{{ today | date }}</p>

Key Point: You can also create custom pipes using @Pipe.

9. Forms

Definition: Angular provides two types of forms:

  • Template-driven (simple, suitable for small apps)
  • Reactive forms (more control, suitable for large apps)

Template-driven Example

JavaScript
<input [(ngModel)]="user.name">

Reactive Example

JavaScript
this.form = new FormGroup({
  name: new FormControl('')
});

Key Point: Import ReactiveFormsModule or FormsModule based on the type of form.

10. HTTPClient

Definition: Angular’s HttpClient is used to make HTTP requests to a backend server.

Example

JavaScript
this.http.get('https://api.example.com/data').subscribe(result => {
  console.log(result);
});

Key Point: Import HttpClientModule and inject HttpClient in the constructor.

11. Event Handling

Definition: Event handling lets you respond to user actions like clicks or input changes.

Example

JavaScript
<button (click)="onClick()">Click Me</button>
JavaScript
onClick() {
  alert('Button clicked!');
}

Key Point: Use event binding syntax (event)="handler()".

12. Template Reference Variable

Definition: Template variables give you a reference to DOM elements in your HTML.

Example

JavaScript
<input #userInput>
<button (click)="log(userInput.value)">Log</button>

Key Point: Template variables start with #.

13. ngFor and ngIf

Definition: Used to display lists or conditionally show/hide elements.

Example

JavaScript
<li *ngFor="let item of items">{{ item }}</li>
<div *ngIf="isLoggedIn">Welcome</div>

Key Point: Use trackBy in ngFor for better performance.

14. @Input and @Output

Definition

  • @Input passes data into a component.

  • @Output sends data out using EventEmitter.

Example

JavaScript
@Input() title: string;
@Output() clicked = new EventEmitter<void>();

Key Point: Use these to communicate between parent and child components.

15. Angular CLI Commands

Definition: CLI helps you create and manage Angular apps.

Common Commands

  • ng new app-name: Create a new app
  • ng serve: Run the app locally
  • ng generate component name: Create a component
  • ng build: Build the app for production

Key Point: CLI automates repetitive tasks.

16. Interceptors

Definition: Interceptors are used to modify HTTP requests or responses globally (for example, adding auth tokens or handling errors).

Example:

JavaScript
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    const token = 'my-token';
    const authReq = req.clone({
      headers: req.headers.set('Authorization', `Bearer ${token}`)
    });
    return next.handle(authReq);
  }
}

Key Point: Register interceptors in providers using { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }.

17. Guards (Route Protection)

Definition: Guards control access to routes based on logic like login status or user roles.

Types: CanActivate, CanDeactivate, CanLoad, Resolve

Example

JavaScript
@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(): boolean {
    return isUserLoggedIn(); // your custom logic
  }
}

Key Point: Attach guards in the route configuration.

18. Lazy Loading

Definition: Lazy loading loads modules only when needed, reducing the initial load time.

Example

JavaScript
const routes: Routes = [
  { path: 'admin', loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule) }
];

Key Point: Use loadChildren in the routing module for lazy loading.

19. Standalone Components (Angular 14+)

Definition: Components that do not need to be declared inside a module. Useful for simpler architecture and micro frontends.

Example

JavaScript
@Component({
  standalone: true,
  selector: 'app-simple',
  template: '<p>Standalone works!</p>',
  imports: [CommonModule]
})
export class SimpleComponent {}

Key Point: Use them for lightweight or isolated features.

20. Environment Files

Definition: Store different settings (like API URLs) for development and production.

Example:

JavaScript
// environment.ts
export const environment = {
  production: false,
  apiUrl: 'http://localhost:3000'
};

Key Point: Use environment.apiUrl in services to avoid hardcoding URLs.

21. TrackBy with ngFor

Definition: Improves rendering performance by identifying items uniquely.

Example

JavaScript
<li *ngFor="let item of items; trackBy: trackById">{{ item.name }}</li>
JavaScript
trackById(index: number, item: any) {
  return item.id;
}

Key Point: Always use trackBy when rendering large lists.

22. Content Projection (ng-content)

Definition: Allows you to insert custom HTML content into a component.

Example

JavaScript
<!-- In reusable component -->
<div class="box">
  <ng-content></ng-content>
</div>
JavaScript
<!-- Usage -->
<app-box>
  <p>This content goes inside the box</p>
</app-box>

Key Point: Use for building reusable UI components like modals and cards.

23. ViewChild and ViewChildren

Definition: Access DOM elements or child components from the class.

Example

JavaScript
@ViewChild('myInput') inputRef: ElementRef;

ngAfterViewInit() {
  console.log(this.inputRef.nativeElement.value);
}

Key Point: Access is available only after ngAfterViewInit().

24. Custom Directive

Definition: Create your own directive to change element behavior.

Example

JavaScript
@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor(el: ElementRef) {
    el.nativeElement.style.backgroundColor = 'yellow';
  }
}

Key Point: Directives add custom behavior to HTML elements.

25. State Management (Basics)

Definition: Managing shared data across components.

Approaches

  • Service with RxJS
  • NgRx (Redux-style)
  • Component Input/Output

Example (RxJS)

JavaScript
private data = new BehaviorSubject<string>('initial');
data$ = this.data.asObservable();

Key Point: Use shared services and Observables to manage app state without tight coupling.

26. Animations

Definition: Angular provides animation support via @angular/animations.

Example

JavaScript
trigger('fadeIn', [
  transition(':enter', [
    style({ opacity: 0 }),
    animate('500ms', style({ opacity: 1 }))
  ])
])

Key Point: Import BrowserAnimationsModule in AppModule to enable animations.

27. Change Detection Strategy

Definition: Angular runs change detection to update the view when data changes. You can control this behavior using strategies.

Types

  • Default: Checks all components.
  • OnPush: Only checks when input changes or events occur.

Example

JavaScript
@Component({
  selector: 'app-sample',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `<p>{{ data }}</p>`
})
export class SampleComponent { }

Key Point: Use OnPush to boost performance in large apps.

28. Error Handling (Global and Local)

Local Example

JavaScript
this.http.get('/data').subscribe({
  next: data => console.log(data),
  error: err => console.error('Error:', err)
});

Global Error Handler

JavaScript
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
  handleError(error: any) {
    console.error('Global Error:', error);
  }
}

Key Point: Always log and handle errors gracefully.

29. Async Pipe

Definition: Automatically subscribes to Observables in templates and unsubscribes when the component is destroyed.

Example

JavaScript
<p>{{ user$ | async }}</p>

Key Point: Avoid manual subscriptions when possible. Prevents memory leaks.

30. Unsubscribe from Observables

Problem: If you forget to unsubscribe, memory leaks can happen.

Solution

JavaScript
private destroy$ = new Subject<void>();

ngOnDestroy() {
  this.destroy$.next();
  this.destroy$.complete();
}

Key Point: Always unsubscribe from long-living Observables like interval() or HttpClient.

31. Structural Directive with ng-template

Definition: Define a template to render conditionally or repeatedly.

Example

JavaScript
<ng-template [ngIf]="show" [ngIfElse]="elseBlock">Visible</ng-template>
<ng-template #elseBlock>Hidden</ng-template>

Key Point: ng-template helps when you want full control over rendering.

32. Custom Pipe

Definition: Create your own pipe to format data.

Example

JavaScript
@Pipe({ name: 'capitalize' })
export class CapitalizePipe implements PipeTransform {
  transform(value: string): string {
    return value.charAt(0).toUpperCase() + value.slice(1);
  }
}

Key Point: Custom pipes are stateless functions used in templates.

33. Reusable Shared Module

Definition: A module that contains common components, directives, and pipes used across the app.

Example

JavaScript
@NgModule({
  declarations: [HeaderComponent, FooterComponent],
  exports: [HeaderComponent, FooterComponent]
})
export class SharedModule { }

Key Point: Import SharedModule wherever common elements are needed.

34. Feature Modules

Definition: Organize your app into multiple modules for better scalability.

Example: UserModule, AdminModule, AuthModule

Key Point: Each module should focus on a single area of the application.

35. Module Preloading

Definition: Load lazy-loaded modules in the background after the app starts.

Example

JavaScript
RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })

Key Point: Improves user experience by reducing wait time when navigating.

36. Angular Universal (SSR)

Definition: Server-side rendering for Angular apps. Helps with SEO and faster initial loading.

Key Point: Use @nguniversal/express-engine to set up SSR.

37. Web Workers

Definition: Run heavy tasks in a separate thread to keep UI responsive.

Key Point: Use Angular CLI to generate workers:

JavaScript
ng generate web-worker my-worker

38. ViewEncapsulation

Definition: Controls how styles are applied to components.

Types

  • Emulated (default)
  • ShadowDom
  • None

Example

JavaScript
@Component({
  encapsulation: ViewEncapsulation.None
})

Key Point: Choose based on your CSS scoping needs.

39. Testing with Jasmine and Karma

Definition: Angular uses Jasmine for writing tests and Karma for running them.

Example

JavaScript
it('should create the app', () => {
  const fixture = TestBed.createComponent(AppComponent);
  const app = fixture.componentInstance;
  expect(app).toBeTruthy();
});

Key Point: Always write unit tests for components and services.

40. Internationalization (i18n)

Definition: Supports multiple languages in Angular apps.

Key Point: Use Angular’s i18n module or third-party libraries like ngx-translate.

Conclusion

You now have a complete Angular cheatsheet that covers everything from beginner to intermediate and even advanced topics. Mastering Angular means understanding not only how components, services, and routing work but also how to manage performance, structure large projects, test effectively, and write clean, maintainable code.