Skip to main content

Angular Interview Cheat Sheet

Top 50 interview questions with concise answers. Print this page or save as PDF for offline study.

View All Angular Questions

1. Whai is angular

Angular is a TypeScript-based frontend framework by Google for building single-page applications. It provides component-based architecture, two-way data binding, dependency injection, and a complete toolset including routing, forms, HTTP client, and CLI. Unlike React (a library), Angular is a full framework with opinionated structure.

2. What is Angular and why is it used?

Angular is a TypeScript framework by Google for building SPAs. It provides: components (UI building blocks), dependency injection (manage services), routing (navigate pages), reactive forms, HTTP client, and change detection. Used for large-scale enterprise apps where consistency, tooling, and TypeScript support matter. Strong opinionated structure vs React's flexibility.

3. What are Angular Components?

Components are the core building blocks of Angular UIs. Each component has: a TypeScript class (logic), HTML template (view), CSS styles, and a @Component decorator that ties them together. Components are reusable, encapsulated, and compose to build the full UI. Everything visible in an Angular app is rendered through a component tree.

4. What is a Module in Angular?

NgModule organizes Angular code into cohesive feature groups. It declares components, directives, and pipes; imports other modules; exports things for other modules to use; and provides services. AppModule is the root. Feature modules group related functionality. Lazy-loaded modules enable code splitting. Angular 14+ standalone components reduce the need for NgModule.

5. What is Data Binding in Angular?

Data binding connects component data to the template. Four types: Interpolation {{value}} (display), Property binding [property]="value" (DOM property), Event binding (click)="handler()" (DOM events), Two-way binding [(ngModel)]="value" (combines property + event binding). Two-way binding is syntactic sugar: [(x)] expands to [x] + (xChange).

6. What are Directives in Angular?

Directives are classes that add behavior to DOM elements. Three types: Component (a directive with a template), Structural (*ngIf, *ngFor, *ngSwitch - alter DOM structure by adding/removing elements), Attribute ([ngClass], [ngStyle], custom - modify element appearance or behavior without changing structure). Custom directives encapsulate reusable DOM behavior.

7. What is Dependency Injection in Angular?

Angular DI is a design pattern where services (dependencies) are provided to components/services that need them rather than created inside them. Angular's injector creates and caches service instances. Declare services with @Injectable, register them in providers, and inject via constructor parameters. DI enables loose coupling, testability, and service sharing across components.

8. Explain Angular Lifecycle Hooks.

Lifecycle hooks let you run code at specific phases of a component's life. Key hooks: ngOnInit (after inputs are set - good for data fetching), ngOnChanges (when input properties change), ngOnDestroy (cleanup - unsubscribe observables, clear timers), ngAfterViewInit (after view and child views are initialized). Implement the corresponding interface (OnInit, OnDestroy etc.).

9. What is Angular Change Detection?

Change Detection checks if component data has changed and updates the DOM accordingly. Angular runs change detection after every browser event, timer, or HTTP call (via Zone.js intercepting async operations). The default strategy checks every component. OnPush strategy only checks a component when its input references change or an event originates from it - much more efficient.

10. What is the Angular CLI and why is it needed?

Angular CLI (ng) is a command-line tool for creating, building, testing, and deploying Angular apps. Commands: ng new (create project), ng generate (create components/services/modules), ng serve (dev server with hot reload), ng build (production build with optimization), ng test (run unit tests), ng lint. It handles webpack configuration, TypeScript compilation, and optimization automatically.

11. What is Ahead-of-Time (AOT) Compilation in Angular?

AOT compiles Angular templates and TypeScript to JavaScript at build time (not in the browser at runtime). Benefits: faster rendering (no template compilation in browser), smaller bundle (template compiler not shipped), earlier error detection (template errors caught at build time), and better security (no eval() at runtime). AOT is enabled by default in ng build --prod.

12. What are Angular Pipes and where are they used?

Pipes transform data in templates for display. Built-in pipes: date, currency, number, percent, uppercase, lowercase, json, slice, async. Usage: {{value | pipeName:param}}. Async pipe automatically subscribes to Observables/Promises and unsubscribes on destroy. Create custom pipes with @Pipe decorator and transform() method. Pure pipes only re-run when input reference changes.

13. Explain Angular Services and their role in an application.

Services are singleton classes that handle business logic, data fetching, and state sharing between components. Decorated with @Injectable. Injected via constructor DI. By default (providedIn: root) a single instance is shared across the whole app. Services keep components lean - components handle display, services handle data and logic. Communication between unrelated components goes through services.

14. What are Observables in Angular and why are they important?

Observables are lazy data streams from RxJS. Angular uses them for HTTP calls (HttpClient returns Observables), routing events, form value changes, and more. Observables support operators (map, filter, switchMap) for transforming and combining streams. Unlike Promises, Observables are cancellable and can emit multiple values over time. Unsubscribe to prevent memory leaks.

15. What is Angular Routing and how does it work?

Angular Router maps URLs to components. Define routes in an array: [{path: "users", component: UsersComponent}]. RouterModule.forRoot() registers routes. is where routed components are rendered. Navigate with routerLink directive or Router.navigate() in code. Supports nested routes, lazy loading, guards, and URL parameters.

16. What are Route Guards and when do you use them?

Route guards control navigation to/from routes. Types: CanActivate (can user navigate to this route?), CanDeactivate (can user leave this route - unsaved changes warning), CanLoad (can lazy-loaded module be loaded?), Resolve (pre-fetch data before route activates). Return true to allow, false to block, UrlTree to redirect. Guards are services implementing the guard interfaces.

17. What is Lazy Loading in Angular and why is it essential?

Lazy loading loads Angular modules on demand when their route is first accessed, instead of loading everything upfront. Benefits: smaller initial bundle, faster initial load. Configure with loadChildren: () => import("./feature/feature.module").then(m => m.FeatureModule). Angular 14+ supports standalone lazy loading: loadComponent. Essential for large apps - users only download code they actually use.

18. What is the difference between Template-driven and Reactive Forms?

Template-driven forms: simpler, uses ngModel directive, two-way binding, logic in template. Good for simple forms. Reactive forms: form model defined in TypeScript (FormControl, FormGroup, FormArray), more powerful validation, better testability, no template logic. Reactive forms are explicit and predictable. For complex forms with dynamic fields, validations, and testing - always use reactive.

19. What is the purpose of Zones in Angular (Zone.js)?

Zone.js patches all browser async APIs (setTimeout, Promise, fetch, event listeners) to notify Angular when async operations complete. This is how Angular knows when to run change detection automatically. NgZone.runOutsideAngular() lets you run code without triggering change detection (useful for performance-heavy operations like animations or setInterval that don't need UI updates).

20. What is ChangeDetectionStrategy.OnPush and when should you use it?

OnPush change detection tells Angular to only check a component when: its input references change (shallow comparison), an event originates from the component or its children, or async pipe receives a new value, or detectChanges() is called manually. This dramatically reduces the number of checks. Use for "dumb" components that only render inputs. Combined with immutable data, it eliminates unnecessary re-renders.

21. What is ViewChild and why is it used?

ViewChild queries a single child element, component, or directive from the view. @ViewChild(ChildComponent) child: ChildComponent gives you a reference to access the child's public methods and properties. Available after ngAfterViewInit. ContentChild queries projected content. Use for: accessing template reference variables, controlling child component behavior, integrating third-party libraries that need DOM references.

22. What is a Component in Angular and what are its key responsibilities?

Angular component responsibilities: define the view (HTML template), manage view state (component class properties), handle user interactions (event handlers), communicate with parent via Output events and receive parent data via Input properties, and coordinate with services for data. Keep components focused on display - delegate business logic and data access to services.

23. Explain Angular Lifecycle Hooks and why they matter.

Angular lifecycle: constructor (DI), ngOnChanges (input changes), ngOnInit (initialization, data fetch), ngDoCheck (custom change detection), ngAfterContentInit/Checked (projected content), ngAfterViewInit/Checked (view children ready), ngOnDestroy (cleanup). ngOnInit is where you fetch initial data. ngOnDestroy is where you unsubscribe all Observables to prevent memory leaks.

24. What is the purpose of NgModule in Angular?

NgModule groups related Angular code. Metadata: declarations (components, directives, pipes owned by this module), imports (other modules needed), exports (what other modules can use), providers (services), bootstrap (root component). AppModule is the root module. Feature modules organize by feature. Shared module exports reusable components. Core module holds app-wide singleton services.

25. What is Dependency Injection (DI) and how does Angular implement it?

Angular DI: services are registered in providers and instantiated by the Angular injector. When a component declares a dependency in its constructor, Angular looks up the injector tree for a provider. providedIn: "root" creates a singleton for the whole app. Component-level providers create a new instance per component instance. Child injectors inherit from parent injectors.

26. What is the difference between Component-level and Module-level Service Providers?

Component-level providers (in @Component providers[]) create a new service instance per component - not shared. Module-level providers (in @NgModule providers[]) are shared across all components in that module. Root-level (providedIn: "root") creates one singleton shared app-wide. Choose based on sharing needs: root for app-wide singletons, component for isolated instances (like form validation state).

27. What are Structural Directives and Attribute Directives?

Structural directives change DOM structure - they add, remove, or manipulate elements. Examples: *ngIf (conditionally renders), *ngFor (repeats for each item), *ngSwitch. The asterisk is syntactic sugar for . Attribute directives change element appearance or behavior without altering structure. Examples: [ngClass], [ngStyle], custom directives that highlight on hover or show tooltips.

28. What is Change Detection in Angular and how does it work?

Change Detection (CD) checks if component model has changed and updates the DOM. Zone.js detects async operations and triggers CD. Angular traverses the component tree top-down checking each component. Default strategy: check all components on every CD cycle. OnPush: check only when inputs change or local event fires. Use OnPush for performance optimization in large component trees.

29. What is the difference between Template Binding Types in Angular?

Angular template binding types: Interpolation {{expr}} for text content. Property binding [prop]="expr" for DOM properties (not attributes). Attribute binding [attr.name]="expr" for HTML attributes (when no DOM property exists). Class binding [class.active]="bool". Style binding [style.color]="expr". Event binding (event)="handler($event)". Two-way [(ngModel)]="field". Each serves a different DOM update purpose.

30. What is Content Projection and why do we use it?

Content projection (ng-content) lets a parent component pass markup into a child component's template. The child template defines placeholder where injected content appears. Useful for creating flexible wrapper components (cards, modals, tabs) that don't know their content in advance. Multi-slot projection: projects only elements with class "header".

31. What is Ahead-of-Time (AOT) Compilation in Angular?

AOT compiles Angular templates at build time on the developer's machine, not at runtime in the browser. Benefits: faster app startup (browser runs pre-compiled code), smaller bundle size (Angular compiler not included in the bundle), template errors caught early, and better security (HTML/JS injection not possible since templates are pre-compiled). Default in production builds.

32. What triggers Change Detection in Angular, and why is understanding this important?

Change Detection triggers: any browser event (click, keyup), XHR response, timer (setTimeout, setInterval), Promise resolution. Zone.js patches all these to notify Angular. Avoid triggering CD unnecessarily: run non-UI work outside Angular zone (NgZone.runOutsideAngular), use OnPush strategy, use pure pipes, debounce frequent events. Understanding triggers is key to performance optimization.

33. What is the difference between Angular’s Default and OnPush Change Detection Strategies?

Default strategy: Angular checks every component on every change detection cycle (conservative but can be slow for large trees). OnPush strategy: Angular skips a component unless its @Input references changed, an event fired from it, or async pipe received new value. OnPush is a performance contract - you tell Angular "I'll manage state immutably so you can skip me." Requires discipline with data mutation.

34. What are Pure and Impure Pipes and how do they affect performance?

Pure pipes: run only when input reference changes (default). Angular caches the result - same input = same output = no recomputation. Impure pipes: run on every change detection cycle regardless of input changes. Impure pipes are expensive and should be avoided for frequently rendering components. Use impure pipes only when necessary (e.g., async pipe which must track subscriptions).

35. What is RxJS and why is it so important in Angular?

RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using Observables. Angular uses RxJS throughout: HttpClient returns Observables, Router events are Observables, reactive form values are Observables. RxJS operators (map, filter, switchMap, debounceTime) enable powerful async data transformation. Understanding RxJS is essential for idiomatic Angular development.

36. What are Hot and Cold Observables and how do they differ?

Cold observable: starts executing when subscribed, each subscriber gets their own execution (e.g., HttpClient - each subscribe makes a separate HTTP call). Hot observable: executing regardless of subscribers, all subscribers share the same execution (e.g., mouse events, WebSocket). Important distinction: subscribing to a cold HTTP Observable twice makes two HTTP requests. Use shareReplay() to make cold observables hot.

37. What is Subject, BehaviorSubject, and ReplaySubject?

Subject: both Observable and Observer - can emit values and subscribe. Used for custom events. BehaviorSubject: remembers and replays the last value to new subscribers, requires initial value - use for current state (like selectedUser$). ReplaySubject: replays N last values to new subscribers - use when late subscribers need history. All are multicast - multiple subscribers share one execution.

38. What is Angular Module Federation, and why is it relevant in large applications?

Module Federation (Webpack 5 feature used by Angular) allows multiple independently deployed Angular apps to share components and code at runtime. Enables micro-frontend architecture: Shell app loads remote apps/modules dynamically from different deployments. Teams deploy independently, share a design system. Angular CLI supports it via @angular-architects/module-federation.

39. What is the role of Angular Zones, and when might you disable them?

NgZone wraps async operations to trigger change detection automatically. Zone.js patches browser APIs to track async activity. Disable zones (zone: "noop" in main.ts) for very performance-sensitive apps - you then manage change detection manually. Run code outside Angular zone with NgZone.runOutsideAngular() for non-UI async work (WebWorkers, setInterval for counters, third-party animations).

40. What is Tree-Shaking and how does Angular benefit from it?

Tree-shaking is a build optimization that removes unused code from the final bundle. Angular's build system (via Webpack/Rollup) analyzes imports and removes code that's never actually used. Angular's standalone components, providedIn: "root" services, and pure functions all support tree-shaking. This is why unused Angular features don't bloat the bundle.

41. What is ViewEncapsulation in Angular and what modes does it support?

ViewEncapsulation controls how component CSS is scoped. Emulated (default): Angular adds unique attributes to elements and scopes CSS to match - styles don't leak. ShadowDom: uses native Shadow DOM for real isolation. None: styles are global and leak everywhere. Emulated is the best default - provides isolation without Shadow DOM browser compatibility concerns.

42. What problem does NgRx solve, and when should it be used instead of simple services?

NgRx solves complex shared state management. Use it when: multiple components need the same state, state changes trigger complex side effects, you need time-travel debugging, or state logic is hard to test in services. For simple apps, services with BehaviorSubjects are sufficient. NgRx adds boilerplate - only adopt when service-based state management becomes unmanageable.

43. Explain the core building blocks of NgRx Store and how they work together.

NgRx building blocks: Store (single source of truth - the state tree), Actions (events describing what happened), Reducers (pure functions that compute new state from action + previous state), Selectors (pure functions to derive/slice state), Effects (handle side effects like HTTP calls, triggered by actions, dispatch new actions). Unidirectional data flow: component dispatches action -> reducer updates store -> component reads selector.

44. What is the difference between Reactive Forms and Template-Driven Forms?

Reactive Forms: FormGroup/FormControl defined in TypeScript, more control, easier to test, dynamic forms, better for complex validation. Template-Driven: uses ngModel in template, less code for simple forms, harder to test, validation in template. Reactive forms scale better for complex scenarios. Template-driven forms are fine for simple cases. Reactive is the recommended approach for enterprise Angular apps.

45. How do Angular Guards work internally and what types exist?

Guards are services implementing guard interfaces. Angular Router calls them before activating/deactivating routes. CanActivate: blocks unauthenticated access. CanDeactivate: warns about unsaved changes. CanLoad: prevents lazy module download for unauthorized users (unlike CanActivate which loads the module then blocks). Resolve: fetches data before the route component initializes. Modern Angular uses functional guards (plain functions).

46. What is the purpose of the Angular Router Outlet and how does routing technically work?

RouterOutlet is a placeholder directive that Angular fills with the routed component. When navigation occurs, Router matches the URL to a route config, loads the component (lazy or eager), and renders it inside the nearest RouterOutlet. Nested routing: child routes render in a child RouterOutlet defined in the parent component's template. Multiple named outlets support complex layouts.

47. What is Lazy Loading in Angular and why is it important?

Lazy loading splits the app into feature modules that load on demand. Configure: {path: "admin", loadChildren: () => import("./admin/admin.module").then(m => m.AdminModule)}. The admin bundle is only downloaded when user navigates to /admin. Reduces initial bundle size dramatically. Angular 14+ also supports standalone component lazy loading without modules.

48. What is Preloading Strategy in Angular?

Preloading strategies load lazy modules in the background after the initial app loads, so navigation feels instant. PreloadAllModules: preloads all lazy modules after init. Custom strategy: implement PreloadingStrategy to selectively preload (e.g., preload based on user role or flag). QuicklinkStrategy preloads modules for routes visible in viewport. Balance between initial load and preload bandwidth usage.

49. What is the role of ChangeDetectorRef and when should it be used?

ChangeDetectorRef gives manual control over change detection. detach() removes a component from the CD tree (must manually call detectChanges()). markForCheck() marks an OnPush component to be checked on next CD cycle (useful when data changes externally). detectChanges() synchronously runs CD on this component and its children. Use when integrating non-Angular code that changes state without triggering Zone.js.

50. What are Angular Schematics and why are they used?

Angular Schematics are code generators used by Angular CLI (ng generate). They automate creating files with proper structure, updating NgModule declarations, and following project conventions. Write custom schematics to enforce team standards: auto-generate boilerplate, apply company conventions to new components, add required files (story files, test files) automatically.
Ready to level up? Start Practice