Skip to main content

Amazon Interview Angular Interview Questions

Curated Amazon Interview-level Angular interview questions for developers targeting amazon interview positions. 120 questions available.

Last updated:

Angular Interview Questions & Answers

Skip to Questions

Welcome to our comprehensive collection of Angular interview questions and answers. This page contains expertly curated interview questions covering all aspects of Angular, from fundamental concepts to advanced topics. Whether you're preparing for an entry-level position or a senior role, you'll find questions tailored to your experience level.

Our Angular interview questions are designed to help you:

  • Understand core concepts and best practices in Angular
  • Prepare for technical interviews at all experience levels
  • Master both theoretical knowledge and practical application
  • Build confidence for your next Angular interview

Each question includes detailed answers and explanations to help you understand not just what the answer is, but why it's correct. We cover topics ranging from basic Angular concepts to advanced scenarios that you might encounter in senior-level interviews.

Use the filters below to find questions by difficulty level (Entry, Junior, Mid, Senior, Expert) or focus specifically on code challenges. Each question is carefully crafted to reflect real-world interview scenarios you'll encounter at top tech companies, startups, and MNCs.

Questions

120 questions
Q1:

Whai is angular

Entry

Answer

Angular is a TypeScript-based front-end framework developed and maintained by Google.
It is used to build single-page applications (SPA) and large-scale web applications.


It provides features like components, modules, routing, two-way data binding, dependency injection, and built-in tooling through Angular CLI.

Quick Summary: 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.
Q2:

What is Angular and why is it used?

Entry

Answer

Angular is a TypeScript-based front-end framework for building scalable and maintainable web applications. It provides components, routing, forms, HTTP, and strong structure for enterprise-level apps.

It is used because it offers TypeScript support, component architecture, built-in tooling, and a complete ecosystem for developing large applications.

Quick Summary: 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.
Q3:

What are Angular Components?

Entry

Answer

Components are the smallest UI building blocks in Angular. They include a template (HTML), a class (TypeScript), and metadata.

Components help create modular, reusable, and structured user interfaces.

Quick Summary: 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.
Q4:

What is a Module in Angular?

Entry

Answer

Angular modules (NgModules) group related components, directives, pipes, and services.

They organize app features, enable lazy loading, and manage visibility of components.

Quick Summary: 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.
Q5:

What is Data Binding in Angular?

Entry

Answer

Data binding connects the component class and the template.

Types include interpolation, property binding, event binding, and two-way binding.

Quick Summary: 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).
Q6:

What are Directives in Angular?

Entry

Answer

Directives are instructions applied to DOM elements.

Types include structural directives (*ngIf, *ngFor) and attribute directives (ngClass, ngStyle).

Quick Summary: 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.
Q7:

What is Dependency Injection in Angular?

Entry

Answer

Dependency Injection provides required services to components automatically.

It improves testability, reduces coupling, and organizes application logic.

Quick Summary: 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.
Q8:

Explain Angular Lifecycle Hooks.

Entry

Answer

Lifecycle hooks allow running code at specific moments such as initialization, change detection, and destruction.

Important hooks include ngOnInit, ngOnDestroy, and ngOnChanges.

Quick Summary: 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.).
Q9:

What is Angular Change Detection?

Entry

Answer

Change detection updates the view automatically when component data changes.

Angular uses Zone.js to track async events and re-render components when needed.

Quick Summary: 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.
Q10:

What is the Angular CLI and why is it needed?

Entry

Answer

Angular CLI is a command-line tool used to create projects, generate components, run builds, and perform testing.

It standardizes development and improves productivity.

Quick Summary: 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.
Q11:

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

Entry

Answer

AOT compiles Angular templates during the build process instead of in the browser.

It produces faster load times, smaller bundles, and more secure applications compared to JIT compilation.

Quick Summary: 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.
Q12:

What are Angular Pipes and where are they used?

Entry

Answer

Pipes are data transformation tools used inside Angular templates. They take input data, apply formatting, and return a transformed output.

Common uses include formatting dates, numbers, currency, converting text case, and filtering lists. Angular supports pure and impure pipes depending on performance and data needs.

Quick Summary: 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.
Q13:

Explain Angular Services and their role in an application.

Entry

Answer

Services contain shared or reusable logic that should not be placed inside components.

They are commonly used for HTTP calls, state management, business logic, utilities, and data sharing. Angular services work with Dependency Injection for clean structure and testability.

Quick Summary: 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.
Q14:

What are Observables in Angular and why are they important?

Entry

Answer

Observables represent asynchronous or event-based data streams. Angular uses RxJS Observables for HTTP requests, user inputs, route events, and real-time updates.

Observables support cancelling, multiple values, and powerful operators, making them ideal for reactive UI development.

Quick Summary: 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.
Q15:

What is Angular Routing and how does it work?

Entry

Answer

Angular Routing enables navigation between components based on the URL. It maps paths to components and allows navigation without page reload.

It supports route parameters, query parameters, guards, and lazy loading, enabling SPA behavior.

Quick Summary: 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.
Q16:

What are Route Guards and when do you use them?

Entry

Answer

Route guards control whether navigation to a route should be allowed or blocked.

Common guards include CanActivate, CanDeactivate, Resolve, CanLoad, and CanActivateChild. They are used for authentication, authorization, saving unsaved data, and preloading route data.

Quick Summary: 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.
Q17:

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

Entry

Answer

Lazy loading loads modules only when they are needed, not on initial app startup.

It improves performance by reducing initial bundle size and enables scalable enterprise-level application development.

Quick Summary: 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.
Q18:

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

Entry

Answer

Template-driven forms rely mainly on HTML templates and are suitable for simple forms.

Reactive forms place form logic in the component class, offering more control, better validation, and integration with RxJS—ideal for complex and dynamic forms.

Quick Summary: 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.
Q19:

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

Entry

Answer

Zones track asynchronous operations and notify Angular when to run change detection.

They eliminate the need to manually update the UI after async tasks, simplifying app development.

Quick Summary: 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).
Q20:

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

Entry

Answer

OnPush change detection checks a component only when its input reference changes, an event occurs, or an observable emits.

It improves performance in large, data-heavy applications by reducing unnecessary change detection cycles.

Quick Summary: 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.
Q21:

What is ViewChild and why is it used?

Entry

Answer

ViewChild allows a component to access child components, DOM elements, or directives.

It is useful for calling child methods, reading template references, and interacting with the DOM after view initialization.

Quick Summary: 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.
Q22:

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

Junior

Answer

A component is the fundamental UI building block in Angular, connecting HTML (view), TypeScript (logic), and CSS (styles).

Responsibilities include rendering UI, handling events, managing local state, communicating with other components, data binding, and calling services.

Quick Summary: 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.
Q23:

Explain Angular Lifecycle Hooks and why they matter.

Junior

Answer

Lifecycle hooks are special methods Angular calls during component creation, update, and destruction.

They help with initialization, loading data, reacting to input changes, accessing the DOM, and cleaning up resources.

Quick Summary: 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.
Q24:

What is the purpose of NgModule in Angular?

Junior

Answer

NgModule groups components, directives, pipes, and services into a logical unit.

It manages imports, exports, providers, compilation context, and enables lazy loading.

Quick Summary: 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.
Q25:

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

Junior

Answer

Dependency Injection provides required objects (services) to classes instead of creating them internally.

Angular uses injectors, providers, and a hierarchical DI system. Constructor injection is the most common mechanism.

Quick Summary: 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.
Q26:

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

Junior

Answer

Component-level services create a new instance for each component instance.

Module-level services provide a shared instance across the entire module/application.

Quick Summary: 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).
Q27:

What are Structural Directives and Attribute Directives?

Junior

Answer

Structural directives change the DOM structure (e.g., *ngIf, *ngFor).

Attribute directives change the appearance or behavior of an element (e.g., ngClass, ngStyle).

Quick Summary: 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.
Q28:

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

Junior

Answer

Change detection updates the UI when data changes. Angular checks component trees after async events using Zone.js.

Two strategies exist: Default (checks all components) and OnPush (checks only when needed).

Quick Summary: 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.
Q29:

What is the difference between Template Binding Types in Angular?

Junior

Answer

Angular supports interpolation, property binding, event binding, and two-way binding.

Each type controls how data flows between component and template.

Quick Summary: 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.
Q30:

What is Content Projection and why do we use it?

Junior

Answer

Content projection allows inserting external content into a component's template.

It enables reusable UI wrappers, flexible layouts, and component composition.

Quick Summary: 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".
Q31:

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

Junior

Answer

AOT compiles Angular templates during build time for faster startup, smaller bundles, earlier error detection, and better security.

AOT is the default for production builds in modern Angular.

Quick Summary: 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.
Q32:

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

Junior

Answer

Angular change detection is triggered by async events handled by Zone.js, such as timers, promises, user events, and HTTP calls.

Understanding these triggers helps avoid unnecessary re-renders, optimize performance, and decide when to use OnPush strategy.

Quick Summary: 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.
Q33:

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

Junior

Answer

Default Strategy: Angular checks all components, even if data has not changed.

OnPush Strategy: Angular checks only when input references change, observables emit, or events occur.

OnPush improves performance, especially in complex apps.

Quick Summary: 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.
Q34:

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

Junior

Answer

Pure Pipes: Run only when input changes, fast and cached.

Impure Pipes: Run on every change detection cycle, can slow performance.

Impure pipes are needed only when data mutates without reference change.

Quick Summary: 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).
Q35:

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

Junior

Answer

RxJS provides observables and operators for handling async programming in Angular.

It powers HTTP requests, forms, router events, websockets, and state management.

Quick Summary: 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.
Q36:

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

Junior

Answer

Cold Observables: Start producing values on subscription (e.g., HTTP calls).

Hot Observables: Produce values regardless of subscribers (e.g., events, websockets).

Cold = fresh execution per subscriber; Hot = shared execution.

Quick Summary: 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.
Q37:

What is Subject, BehaviorSubject, and ReplaySubject?

Junior

Answer

Subject: No initial value; subscribers only receive future values.

BehaviorSubject: Has initial value and gives latest value to new subscribers.

ReplaySubject: Stores a buffer of values and replays them to new subscribers.

Quick Summary: 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.
Q38:

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

Junior

Answer

Module Federation allows multiple Angular applications to share modules or components at runtime.

It enables microfrontends, improves modularity, and supports independent deployments.

Quick Summary: 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.
Q39:

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

Junior

Answer

Zones track async tasks and trigger change detection. Disabling them is useful for high-performance apps that manually control UI updates.

Helps in real-time or graphics-heavy applications.

Quick Summary: 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).
Q40:

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

Junior

Answer

Tree-shaking removes unused code from the bundle.

It results in smaller builds, faster load times, and better performance.

Quick Summary: 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.
Q41:

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

Junior

Answer

ViewEncapsulation controls how component styles are scoped.

Modes: Emulated (default), ShadowDom, and None.

It prevents CSS conflicts and supports reusable component styling.

Quick Summary: 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.
Q42:

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

Mid

Answer

NgRx solves complex application state management problems, especially in large apps where multiple components need shared state.

You should use NgRx when many components read and update global state, require time-travel debugging, offline caching, immutability, or predictable unidirectional data flow.

Small apps do not need NgRx; services or BehaviorSubjects are sufficient.

Quick Summary: 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.
Q43:

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

Mid

Answer

NgRx uses a predictable data flow:

  • Actions: Describe events
  • Reducers: Update state immutably
  • Store: Holds global state
  • Selectors: Retrieve computed data
  • Effects: Handle async operations

The flow is: Actions ? Reducers ? Store ? Selectors ? Components ? Effects ? new Actions.

Quick Summary: 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.
Q44:

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

Mid

Answer

Reactive Forms use TypeScript classes for form control, offer better scalability, testing, dynamic fields, and are suitable for enterprise use.

Template-Driven Forms rely on HTML templates, good for small simple forms but less testable and harder to scale.

Quick Summary: 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.
Q45:

How do Angular Guards work internally and what types exist?

Mid

Answer

Guards run before route activation to allow or block navigation.

Types include: CanActivate, CanDeactivate, CanLoad, CanActivateChild, and Resolve.

They handle security, data preloading, navigation rules, and preventing access to invalid or unauthorized pages.

Quick Summary: 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).
Q46:

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

Mid

Answer

RouterOutlet is a dynamic placeholder where Angular loads components based on the active route.

Routing parses the URL, matches it with route configuration, runs guards/resolvers, and finally loads the mapped component into the outlet.

Quick Summary: 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.
Q47:

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

Mid

Answer

Lazy loading loads feature modules only when required.

This reduces initial bundle size, speeds up first load, improves performance, and helps modularize large enterprise applications.

Quick Summary: 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.
Q48:

What is Preloading Strategy in Angular?

Mid

Answer

Preloading loads lazy-loaded modules in the background after the main app loads.

Benefits include faster navigation and balanced app performance.

Angular provides built-in strategies like PreloadAllModules and supports custom strategies.

Quick Summary: 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.
Q49:

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

Mid

Answer

ChangeDetectorRef gives manual control over Angular’s change detection.

Used when working with OnPush, avoiding heavy re-renders, handling updates outside Angular zones, or running performance-sensitive operations.

Quick Summary: 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.
Q50:

What are Angular Schematics and why are they used?

Mid

Answer

Schematics automate code generation, enforcing consistent structure across the project.

They generate modules, components, upgrade Angular versions, and apply organization-wide architecture rules.

Quick Summary: 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.
Q51:

What is the difference between Shared Module and Core Module in Angular?

Mid

Answer

Shared Module contains reusable components, pipes, and directives and can be imported many times.

Core Module holds global singletons like services, interceptors, and layout components, imported only once.

This separation improves architecture, scalability, and avoids duplicate service instances.

Quick Summary: SharedModule contains components, directives, and pipes used across multiple feature modules. Export what you share, don't provide services (use root or feature-level providers). CoreModule contains app-wide singleton services (auth, logging) and is imported only in AppModule. Import SharedModule in feature modules. CoreModule should throw error if imported twice (to enforce singleton).
Q52:

What is the purpose of Angular zones?

Mid

Answer

Zones track asynchronous operations and automatically trigger change detection.
Without zones, Angular would not know when async tasks like timeouts or HTTP calls finish.
Quick Summary: Angular zones (Zone.js) intercept async operations to detect when the app needs change detection. Zones patch browser APIs like setTimeout, Promise, and event listeners. When any patched async operation completes, Angular knows to run change detection. This is why you don't need to manually trigger UI updates in Angular when data changes asynchronously.
Q53:

What are Angular lifecycle phases in change detection?

Mid

Answer

Angular runs two phases:
Check phase: Verifies bindings.
Update phase: Applies DOM updates and triggers child checks.
This ensures UI consistency.
Quick Summary: Angular CD lifecycle phases: 1) Mark view dirty (async event fires), 2) ApplicationRef.tick() starts CD from root, 3) For each component in tree: check host bindings, run ngDoCheck, check child components recursively, 4) Update DOM for changed components. OnPush skips the subtree unless input changed. ngAfterViewChecked fires after each CD cycle where a view is checked.
Q54:

Difference between template-driven and reactive forms?

Mid

Answer

Template-driven forms rely on template directives and implicit data flow.
Reactive forms use explicit FormControl objects, enabling predictable state, dynamic validation, and easier testing.
Quick Summary: Template-driven: uses directives (ngModel), form logic in template, async validation is complex, less testable, less code for simple cases. Reactive: FormGroup/FormControl in TypeScript, validators are plain functions, dynamic form fields with FormArray, unit-testable without the DOM. Reactive is preferred for any form with complex validation, conditional fields, or dynamic structure.
Q55:

How does Angular handle dependency resolution with multiple providers?

Mid

Answer

Angular uses hierarchical injectors.
If the same token exists in multiple injectors, the nearest injector to the component wins.
Quick Summary: Angular injector tree: when multiple providers for the same token exist at different levels (root, module, component), the injector closest to the consumer wins. The injector walks up the tree until it finds a provider. Use InjectionToken for non-class dependencies. forwardRef() resolves circular dependencies at decoration time. Multi providers (multi: true) merge multiple values for the same token into an array.
Q56:

What is the module-with-providers pattern?

Mid

Answer

Used when modules need root-level configuration.
Allows importing a module multiple times without re-registering global services.
Quick Summary: ModuleWithProviders pattern lets a module export providers that are only configured when imported with forRoot(). RouterModule.forRoot(routes) registers the router globally with routes. RouterModule.forChild(routes) doesn't re-provide the router service. Use this pattern for library modules that need to be configured once at root level but imported in multiple feature modules.
Q57:

Purpose of entryComponents in pre-Ivy Angular?

Mid

Answer

Before Ivy, Angular needed entryComponents to know which components could be created dynamically.
Ivy removed this requirement.
Quick Summary: In pre-Ivy Angular (ViewEngine), entryComponents listed components created dynamically (not via selector in templates) so the compiler would include them in the bundle. Components referenced only in template selectors were automatically included. Ivy made entryComponents obsolete - it uses a different compilation model that discovers all components. In Angular 9+, entryComponents is a no-op.
Q58:

How does Angular parse templates internally?

Mid

Answer

Angular converts templates into Ivy instructions that directly execute, improving performance and eliminating heavy compilation.
Quick Summary: Angular compiler parses template HTML into an AST (Abstract Syntax Tree). It analyzes bindings, directives, pipes, and structural directives. Ivy compiles each component into a set of template instructions (a render function). These instructions directly call Angular runtime APIs to create DOM nodes and set up bindings. This replaces the old ViewEngine approach of generating ngFactory files.
Q59:

How does Angular detach or skip change detection?

Mid

Answer

Using OnPush, ChangeDetectorRef.detach(), or manual checks, Angular can skip change detection for performance optimization.
Quick Summary: Detach from CD: ChangeDetectorRef.detach() removes the component from the CD tree - Angular won't check it automatically. Manually call detectChanges() when needed. Skip CD: OnPush strategy skips components unless inputs change. Run code outside zone: NgZone.runOutsideAngular() prevents zone notifications from triggering CD for non-UI work. These techniques are essential for performance-critical components.
Q60:

How does Angular sanitize DOM?

Mid

Answer

Angular uses DomSanitizer to remove harmful HTML, URLs, and scripts, protecting against XSS attacks.
Quick Summary: Angular sanitizes values bound to innerHTML, style, URL attributes, and resource URLs by default. The DomSanitizer strips dangerous HTML before inserting into DOM (prevents XSS). Property binding [innerHTML] is automatically sanitized. To bypass sanitization (with care): DomSanitizer.bypassSecurityTrust*(). Angular's template syntax safely escapes interpolated values - they're text nodes, not HTML.
Q61:

Difference between value providers and factory providers?

Mid

Answer

Value providers supply literal constants.
Factory providers generate values dynamically using logic or dependencies.
Quick Summary: Value provider: provide a static value for a token (useValue: myConfig). Factory provider: use a function to create the service (useFactory: () => new MyService(dep), deps: [Dep]) - enables conditional creation logic or passing constructor args. Class provider (useClass): use a different class than the token. Existing provider (useExisting): alias one token to another. Factories are for complex initialization logic.
Q62:

How does Angular perform content projection?

Mid

Answer

Angular uses ng-content slots and tracks projected nodes using host views, integrating child templates with parent DOM.
Quick Summary: Angular processes directives at compile time. The component template declares content projection slots with selectors. When Angular renders the component, it moves matching projected elements from the parent template into the slots. Multi-slot projection: for specific content. Projected content belongs to the parent component's view (not the child's).
Q63:

Role of ApplicationRef in Angular?

Mid

Answer

Manages the component tree, performs manual change detection, and supports custom bootstrapping.
Quick Summary: ApplicationRef represents the Angular application. tick() manually runs change detection for the whole app (useful when Zone.js is disabled). attachView() adds a HostView (from ComponentRef) to the app's change detection tree. isStable Observable emits when the app has no pending async work (used for server-side rendering to know when to serialize). Rarely used directly in app code.
Q64:

What happens when creating a component with ViewContainerRef?

Mid

Answer

Angular creates a host view, initializes metadata, sets bindings, and renders template instructions.
Quick Summary: ViewContainerRef.createComponent() dynamically creates a component and inserts it into the DOM at the view container's location. Returns a ComponentRef with the component instance and host view. The created component is added to the host module's CD tree. Destroy with ComponentRef.destroy(). Used for: dynamic dialogs, tooltips, dynamic form fields. More powerful than *ngIf for programmatic creation.
Q65:

Difference between embedded views and host views?

Mid

Answer

Host views belong to components.
Embedded views are created from ng-template or structural directives.
Quick Summary: Embedded view: created from a TemplateRef (ng-template) - renders a reusable template chunk into the DOM. Host view: the view of a dynamically created component (ComponentRef.hostView). Both are ViewRef instances and can be attached to a ViewContainerRef. Structural directives use embedded views: *ngIf creates/destroys an embedded view for the ng-template content.
Q66:

What is the Angular renderer?

Mid

Answer

Renderer abstracts DOM operations, enabling Angular to run in environments like SSR, Web Workers, or NativeScript.
Quick Summary: Angular Renderer2 provides a platform-agnostic API for DOM manipulation. Instead of direct DOM calls (document.createElement, element.style.color), use Renderer2 methods. This allows Angular to run in non-browser environments (SSR, Web Workers, NativeScript). Inject Renderer2 and use: createElement, appendChild, setStyle, setAttribute, addClass, listen. Prefer over direct DOM access for platform independence.
Q67:

How does Angular handle heavy asynchronous UI operations?

Mid

Answer

Uses zone.js, task queues, microtasks, and triggers change detection after async tasks complete.
Quick Summary: Handle heavy async UI operations: use trackBy in *ngFor to minimize DOM re-creation, virtual scrolling (cdk-virtual-scroll-viewport) for long lists, debounce user inputs before processing, run heavy computation in Web Workers (off main thread), use OnPush CD to minimize checks, paginate data instead of loading everything, and use requestAnimationFrame for animation-related work.
Q68:

Difference between template reference and template input variables?

Mid

Answer

Template reference variables refer to DOM or component instances.
Template input variables provide local directive context, such as ngFor.
Quick Summary: Template reference variable (#ref): references a DOM element or component instance in the template. lets you use nameInput.value. Template input variable (let-item): used inside structural directives to reference the current iteration value.
  • - item is a template input variable bound by the *ngFor directive's context.
  • Q69:

    How do Angular directives communicate?

    Mid

    Answer

    Communication via selectors, dependency injection, or parent-child directive references.
    Quick Summary: Directives communicate through: parent-child via DI (inject parent directive in child constructor - same element or ancestor), shared service (both directives inject the same service), host binding/listener (directive reads/modifies host element), or through the component's @Input/@Output if the directive is on a component. Siblings on the same element can reference each other via DI.
    Q70:

    What is PlatformBrowserModule?

    Mid

    Answer

    Provides browser-specific services and bootstrapping required to run Angular apps in a browser.
    Quick Summary: BrowserModule provides browser-specific implementations of Angular services (DOM renderer, browser platform), bootstraps the app, and exports CommonModule (NgIf, NgFor, async pipe etc.). Import BrowserModule only in AppModule (root). Feature modules import CommonModule (included in BrowserModule) instead. Importing BrowserModule in lazy-loaded feature modules throws an error.
    Q71:

    How does Angular handle structural directives internally?

    Mid

    Answer

    Transforms structural directives into template instructions manipulating embedded views.
    Quick Summary: Structural directives use embedded views internally. When you write *ngIf="show", Angular desugars it to: . The directive receives a TemplateRef and ViewContainerRef via DI. It calls viewContainerRef.createEmbeddedView(templateRef) to show and viewContainerRef.clear() to hide. The asterisk is pure syntactic sugar for the ng-template pattern.
    Q72:

    What are host bindings and host listeners?

    Mid

    Answer

    Host bindings bind properties on the host element.
    Host listeners listen to events on the host element.
    Quick Summary: Host bindings and listeners let directives/components interact with their host element. @HostBinding("class.active") isActive: boolean adds class "active" to the host element when isActive is true. @HostListener("click", ["$event"]) onClick(event) handles click events on the host element. Both are Angular's clean alternative to direct DOM manipulation in directives.
    Q73:

    Difference between RouterModule.forRoot and forChild?

    Mid

    Answer

    forRoot creates the global router services.
    forChild adds child routes without recreating router instances.
    Quick Summary: RouterModule.forRoot() registers the Router service and root routes - call once in AppModule. RouterModule.forChild() registers additional routes for a lazy feature module without re-providing the Router service. Calling forRoot() in a lazy module would create a second Router instance and break routing. Feature modules always use forChild().
    Q74:

    How does Angular router reuse strategy work?

    Mid

    Answer

    Determines whether route components should be cached or recreated during navigation.
    Quick Summary: RouteReuseStrategy determines when Angular destroys and recreates components on navigation. Default: component is destroyed when you navigate away and recreated on return. Custom strategy: implement RouteReuseStrategy to cache component state across navigation (useful for list pages where you want scroll position preserved). Angular CDK or custom implementations store/restore detached view trees.
    Q75:

    What is navigation extras?

    Mid

    Answer

    Additional navigation configuration like query params, fragments, state, or skipLocationChange.
    Quick Summary: NavigationExtras are options passed to router.navigate() or router.navigateByUrl(). Options include: queryParams (add URL query parameters), fragment (scroll to anchor), replaceUrl (replace history entry instead of push), skipLocationChange (navigate without updating URL), relativeTo (navigate relative to a route). Example: router.navigate(["/users"], {queryParams: {page: 2}}).
    Q76:

    How does Angular handle slow-loading modules?

    Mid

    Answer

    Uses lazy loading and route splitting so modules load only when needed.
    Quick Summary: Angular handles slow-loading lazy modules with loading indicators via Router events. Listen for NavigationStart (show spinner) and NavigationEnd/NavigationError (hide spinner). Preloading strategies reduce perceived load time by downloading modules in background after initial load. Add a loading component to router config as a placeholder while lazy bundles download.
    Q77:

    How does Angular's animation engine work?

    Mid

    Answer

    Converts animation metadata into CSS or WebAnimation instructions and manages start/cancel/done events.
    Quick Summary: Angular Animations uses the Web Animations API and CSS transitions via @angular/animations. Define state transitions in @Component animations metadata with trigger(), state(), transition(), and animate(). The animation engine applies CSS changes with optimal timing. AnimationBuilder allows programmatic control. Angular animations support sequence(), group(), stagger() for complex choreographed animations.
    Q78:

    Limitations of ChangeDetectionStrategy.OnPush?

    Mid

    Answer

    Requires immutability and manual notifications; otherwise UI may not update automatically.
    Quick Summary: OnPush limitations: if you mutate an object/array in place (push to array, modify nested property), OnPush won't detect the change because the reference is the same. You must create new references (immutable updates). Also, changes from outside Angular's zone (third-party callbacks) won't trigger CD automatically - call markForCheck() or detectChanges() manually. Signals (Angular 17+) solve these limitations.
    Q79:

    Difference between host elements and component elements?

    Mid

    Answer

    Host element is where the component attaches.
    Component elements are internal template nodes.
    Quick Summary: Host element is the DOM element matching a component's or directive's selector. Component element refers to the element the component is applied to. For , the div tag in the parent template is the host element. The component's template content is rendered inside the host element. Host bindings modify the host element itself. Shadow DOM encapsulates styles within the host element boundary.
    Q80:

    How does Angular handle global error handling?

    Mid

    Answer

    Uses ErrorHandler to centralize uncaught errors.
    Custom handlers can log errors or show user-friendly messages.
    Quick Summary: Global error handling in Angular: implement ErrorHandler interface and provide it in AppModule. The handleError() method is called for all uncaught errors. Use it to: log errors to a monitoring service (Sentry, Datadog), show a user-friendly error UI, and handle specific error types differently. HTTP errors should be handled in interceptors or catchError operators, not in the global handler.
    Q81:

    What are Angular Interceptors and how do they work internally?

    Senior

    Answer

    Interceptors act as middleware for all HTTP requests and responses in Angular.

    Internally, Angular creates a chain of interceptor handlers. Each interceptor receives the outgoing request, can clone or modify it, and then passes it to the next handler. Responses flow back in reverse order, allowing global transformations.

    Common uses: authentication tokens, error handling, logging, retry logic, preventing duplicate calls.

    Quick Summary: HTTP Interceptors are middleware for HttpClient. They intercept every HTTP request and response. Common uses: add auth token to every request header, handle 401 errors globally (redirect to login), log requests/responses, show/hide loading spinner, retry failed requests. Interceptors are chained - each can modify request/response and call next() to continue the chain.
    Q82:

    What are the best practices for handling authentication tokens in Angular?

    Senior

    Answer

    Token handling must prioritize security. Best practices include:

    • Store tokens in memory or sessionStorage (avoid localStorage for sensitive apps).
    • Use HttpOnly cookies when backend supports them.
    • Add tokens only through interceptors.
    • Avoid placing tokens in URLs.
    • Implement token refresh + logout on refresh failure.
    • Never expose secrets in frontend code.
    Quick Summary: Auth token best practices in Angular: store tokens in memory (not localStorage - XSS risk) or HttpOnly cookies (CSRF protection needed). Use interceptors to attach tokens to requests automatically. Implement token refresh logic with catchError and retry. Clear tokens on logout. Short-lived access tokens with refresh tokens is the recommended pattern.
    Q83:

    What is Angular Internationalization (i18n) and how does build-time translation work?

    Senior

    Answer

    Angular i18n extracts translatable strings from templates and applies translations at build time.

    The Angular compiler replaces template text with localized versions, generating separate build bundles for each locale. ICU expressions manage pluralization and formatting, improving runtime performance and memory usage.

    Quick Summary: Angular i18n extracts translatable text from templates at build time, merges translation files, and produces separate locale-specific bundles. Each locale is a separate build output. Use message IDs with i18n attribute:

    Hello

    . Extract with ng extract-i18n. Provide XLIFF/XMB translation files per locale. Runtime i18n libraries (ngx-translate) are easier to setup but less performant.
    Q84:

    What is the difference between Content Projection and View Projection?

    Senior

    Answer

    Content Projection inserts external content into a child component's template, enabling reusable layout patterns.

    View Projection uses internal views created by the component via ViewChild, ViewContainerRef, or embedded views.

    Content projection passes external markup; view projection manages internal view trees.

    Quick Summary: Content projection (ng-content): parent passes markup INTO a component - the child controls layout, parent provides content. View projection is not a standard Angular term. ViewChild queries elements within the component's own template. ContentChild queries projected content. Content projection enables reusable container components (cards, panels, dialogs) that accept arbitrary content from parents.
    Q85:

    What is Ahead-of-Time (AOT) Compilation and why is it required in Angular?

    Senior

    Answer

    AOT compiles Angular templates to optimized JavaScript during build, not in the browser.

    Benefits: faster startup, smaller bundles, better security, and earlier error detection. AOT is the default mode for production builds.

    Quick Summary: AOT compiles templates and decorators at build time. Why required: JIT (Just-In-Time) compilation in the browser is slow and ships the compiler as part of the bundle (adds ~40% to bundle size). AOT produces smaller, faster apps - the template compiler isn't needed at runtime. Also catches template errors at compile time. Always use AOT in production; Angular makes it the default.
    Q86:

    How does Angular handle memory management for components and subscriptions?

    Senior

    Answer

    Angular destroys component instances automatically when navigating, but developers must prevent memory leaks by:

    • Unsubscribing Observables using async pipe or takeUntil.
    • Clearing intervals/timeouts.
    • Removing manual event listeners.
    • Avoiding storing component references in services.
    Quick Summary: Memory management in Angular: subscribe creates subscriptions that must be cleaned up. In ngOnDestroy: unsubscribe all Observables, use takeUntil(this.destroy$) pattern, clear intervals. Async pipe auto-unsubscribes when component destroys. Common leaks: subscriptions in services that outlive components, event listeners on window/document not removed, detached DOM nodes holding component references.
    Q87:

    What are Smart and Dumb Components and why are they important?

    Senior

    Answer

    Smart Components handle data fetching, state management, and service interactions.

    Dumb Components focus purely on presentation, using @Input and @Output. They are reusable, testable, and predictable.

    This separation improves scalability and modularity in enterprise Angular applications.

    Quick Summary: Smart (Container) components: manage state, communicate with services, handle data fetching. Dumb (Presentational) components: receive data via @Input, emit events via @Output, no direct service dependencies. Benefits: dumb components are easily reusable, testable (just pass inputs and check outputs), and work naturally with OnPush (inputs are always explicit). Separation of concerns makes the app cleaner.
    Q88:

    Explain Angular's Rendering Pipeline step-by-step.

    Senior

    Answer

    The rendering pipeline steps:

    1. Change detection runs to identify data changes.
    2. Angular updates DOM nodes via compiled instructions.
    3. Directive inputs + lifecycle hooks run.
    4. Browser recalculates styles and layout.
    5. Paint + render occurs.

    Angular optimizes minimal DOM updates for performance.

    Quick Summary: Angular rendering pipeline: TypeScript compilation, template compilation (AOT), change detection runs top-down from root component, dirty components are re-rendered, Virtual DOM diffing (Ivy's incremental DOM approach), and actual DOM is patched with only the changes. Ivy (Angular 9+) generates more efficient, tree-shakable component code compared to the old ViewEngine.
    Q89:

    What are Custom Decorators in Angular and when should they be used?

    Senior

    Answer

    Custom decorators allow attaching metadata or logic to classes, properties, or methods. They are useful for logging, validation, metadata injection, and reducing boilerplate.

    However, overuse can create hidden complexity and should be applied selectively.

    Quick Summary: Custom decorators are functions that add metadata or modify behavior of classes, methods, properties, or parameters. Used for: adding metadata (like @Injectable, @Component), method logging, authorization checks, memoization. Create with TypeScript decorator syntax. Angular itself uses decorators extensively. Useful for cross-cutting concerns but can be hard to debug - use sparingly.
    Q90:

    What are common Angular security risks and how do you mitigate them?

    Senior

    Answer

    Major risks include:

    • XSS – rely on Angular sanitization, avoid bypassSecurityTrust.
    • CSRF – use server-issued anti-forgery tokens or HttpOnly cookies.
    • Sensitive data exposure – never store secrets in the frontend.
    • Clickjacking – enforce frame-ancestors policies on server.
    • API abuse – ensure backend role validation and rate limiting.
    Quick Summary: Angular security risks: XSS (Angular sanitizes HTML binding by default - DomSanitizer bypasses should be reviewed carefully), CSRF (use SameSite cookies or XSRF tokens - HttpClient supports this automatically), component injection attacks (avoid innerHTML with user data), dependency vulnerabilities (keep packages updated), and sensitive data in localStorage (prefer HttpOnly cookies or memory).
    Q91:

    What is Angular Zone (NgZone) and why is it important?

    Senior

    Answer

    NgZone allows Angular to track asynchronous operations such as HTTP requests, timeouts, promises, and events. When these operations complete, Angular triggers change detection to update the UI automatically.

    Developers can execute heavy tasks outside Angular’s zone using runOutsideAngular() to avoid unnecessary change detection and improve performance.

    Quick Summary: NgZone is Angular's wrapper around Zone.js. It runs callbacks inside the Angular zone, which triggers change detection when they complete. run() executes code inside the zone (triggers CD). runOutsideAngular() executes outside the zone (no CD trigger) - use for performance-intensive non-UI work. Important for integrating third-party libraries that do async work not tracked by Angular.
    Q92:

    Explain Angular Change Detection Strategies (Default vs OnPush).

    Senior

    Answer

    Default Strategy: Angular runs change detection for the entire component tree whenever any async event occurs. Simple but expensive for large apps.

    OnPush Strategy: Angular checks the component only when its input reference changes, an observable emits, or an event originates from the component. This dramatically improves performance.

    Quick Summary: Default CD: checks every component on every cycle - simple but potentially slow for large trees. OnPush CD: component is only checked when inputs change (by reference), an event fires from within, async pipe emits, or markForCheck()/detectChanges() is called. OnPush with immutable data patterns dramatically reduces unnecessary DOM checks. Use Angular DevTools to visualize CD cycles.
    Q93:

    What is the Smart vs Dumb Component pattern and why is it used?

    Senior

    Answer

    Smart Components handle data loading, business logic, and state management.

    Dumb Components only display UI, receive input, and emit events.

    This pattern increases reusability, makes components more testable, and keeps UI clean and maintainable.

    Quick Summary: Smart components: connect to services, dispatch NgRx actions, manage state. Dumb/Presentational components: pure input/output, no service dependencies, easily testable, reusable anywhere. Why it matters: dumb components with OnPush change detection are extremely performant and testable. Smart components handle the complexity in one place. Pattern prevents spaghetti data flow in large apps.
    Q94:

    How does Angular handle memory leaks and what causes them?

    Senior

    Answer

    Common leak causes include:

    • Unsubscribed Observables
    • DOM references kept alive
    • Event listeners not removed
    • Intervals/timeouts not cleared

    Angular avoids leaks via async pipe, takeUntil, DestroyRef, and proper cleanup patterns.

    Quick Summary: Angular memory leaks: Observables subscribed in components but never unsubscribed (subscription keeps component alive). Fix: use async pipe (auto-unsubscribes), takeUntilDestroyed() (Angular 16+), or takeUntil with destroy$ Subject. Event listeners on global objects (window, document) added in ngOnInit but not removed in ngOnDestroy. Detached component references in third-party library callbacks.
    Q95:

    Difference between Template-Driven and Reactive Forms (in-depth).

    Senior

    Answer

    Template-Driven Forms: Defined mostly in HTML, suitable for simple forms, limited dynamic capability.

    Reactive Forms: Structured entirely in TypeScript, scalable, predictable, supports dynamic fields, custom validators, and is ideal for enterprise-level applications.

    Quick Summary: Template-Driven: uses [(ngModel)], directives in template, async validation tricky, unit testing harder (needs DOM). Reactive: FormGroup/FormControl in TypeScript, synchronous and async validators as functions, dynamic form building with FormArray, fully testable without DOM. For complex forms with conditional fields, dynamic validation rules, or testing requirements, Reactive is always the right choice.
    Q96:

    How do you debug Angular performance issues?

    Senior

    Answer

    Performance debugging techniques include:

    • Using Angular DevTools to inspect change detection
    • Profiling DOM updates and rerenders
    • Checking unnecessary subscriptions
    • Auditing bundle size and lazy-loading usage
    • Using browser Performance tools to identify bottlenecks
    Quick Summary: Debug Angular performance: Angular DevTools browser extension (visualize component tree, CD cycles, profiler). Enable Angular profiling mode (ng.profiler.timeChangeDetection()). Use Chrome Performance tab to identify long tasks. Common causes: too many CD checks (fix with OnPush), slow pipes (use pure pipes), large lists (use virtual scrolling), unnecessary HTTP calls. Track which components re-render with the profiler.
    Q97:

    What is Server-Side Rendering (SSR) in Angular and how does it work?

    Senior

    Answer

    SSR pre-renders Angular pages on the server using Angular Universal.

    Benefits include improved SEO, faster first contentful paint, better performance on slow devices, and reduced time-to-interactive.

    The server renders HTML ? browser loads it ? Angular hydrates and takes over as a SPA.

    Quick Summary: Angular Universal enables Server-Side Rendering (SSR). The Angular app runs on a Node.js server, renders HTML, and sends it to the browser. Benefits: faster First Contentful Paint (FCP), better SEO (bots see full HTML), social sharing previews. Challenges: server state transfer to client, browser APIs not available on server (window, document). Use TransferState to pass data from server render to client.
    Q98:

    What are Custom Pipes in Angular and when should they be avoided?

    Senior

    Answer

    Custom Pipes transform UI data, but avoid heavy logic inside pipes because they can re-run frequently. Use memoization or pre-computed values when needed to avoid performance issues.

    Quick Summary: Custom pipes transform display values: implement PipeTransform, define transform() method with @Pipe decorator. Example: a truncate pipe that shortens long text. When to avoid: heavy computation inside pipes (runs on every CD cycle unless pure), async operations in pipes (use async pipe instead), or logic that belongs in the component/service. Keep pipes simple and stateless.
    Q99:

    Explain Internationalization (i18n) in Angular.

    Senior

    Answer

    Angular supports:

    • Build-time localization
    • Static translations via Angular i18n
    • Runtime translations via ngx-translate
    • Locale-specific formatting for dates, currency, numbers

    i18n is essential for global and multilingual applications.

    Quick Summary: Angular i18n: mark text with i18n attribute, extract with ng extract-i18n to XLIFF files, translate files per locale, build separate bundles per locale (ng build --localize). Formatted separately per locale means no runtime translation overhead. For runtime translation (without separate builds), ngx-translate library is the alternative. Angular 14+ improved Ivy-based i18n support.
    Q100:

    How do Signals (Angular 17+) improve reactivity compared to Observables?

    Senior

    Answer

    Signals store synchronous reactive values and update the UI automatically without subscriptions.

    They simplify state management, eliminate manual cleanup, and improve performance. Observables remain essential for asynchronous workflows, but signals simplify UI state handling.

    Quick Summary: Angular Signals (Angular 17+) are reactive primitives - a signal holds a value, and anything that reads it is automatically notified when the value changes. Unlike Observables, Signals are synchronous, simpler to use (no subscribe/unsubscribe), and enable fine-grained reactivity (only affected components update). Combined with computed() and effect(), they offer a simpler reactive model than RxJS for most UI state.
    Q101:

    What is the role of RxJS in Angular, and why is it used extensively?

    Expert

    Answer

    RxJS powers Angular’s async architecture—HTTP, events, routing, and UI streams. It provides a reactive, push-based model that supports composition, cancellability, and declarative async workflows. This makes complex UI flows predictable, scalable, and maintainable.

    Quick Summary: RxJS handles all async data flows in Angular. HttpClient returns Observables. Router events are Observables. Reactive form controls emit value changes as Observables. This unified model lets you compose, transform, and combine async data streams with operators. Without RxJS, Angular would use callbacks or Promises - RxJS gives much more powerful composition and cancellation.
    Q102:

    Explain Hot Observable vs Cold Observable.

    Expert

    Answer

    Cold Observables start producing values only when subscribed. Each subscriber gets its own execution (e.g., HTTP calls).

    Hot Observables emit values regardless of subscriptions. Subscribers join an active stream (e.g., events, websockets).

    Quick Summary: Cold observable: each subscriber creates a new independent execution. HTTP calls are cold - every subscribe makes a new request. Hot observable: single execution, all subscribers share it. Mouse events are hot - event happens regardless of subscribers. The distinction matters for avoiding duplicate HTTP calls: use shareReplay(1) to make a cold Observable hot and cache the result.
    Q103:

    What is a Subject in RxJS and why is it used in Angular services?

    Expert

    Answer

    A Subject is both an observable and an observer. Angular uses it for shared service communication, event broadcasting, and maintaining UI state.

    Quick Summary: Subject is both an Observable and Observer - you can call next() to emit values and subscribe() to receive them. In Angular services, use Subject for event buses: private events$ = new Subject(); expose as Observable: asObservable(). Multiple components subscribe to share the same event stream. Unlike BehaviorSubject, Subject doesn't replay last value to new subscribers.
    Q104:

    Explain BehaviorSubject vs ReplaySubject and their use cases.

    Expert

    Answer

    BehaviorSubject stores the latest value and immediately emits it to subscribers—ideal for UI and state.

    ReplaySubject replays a buffer of previous values—ideal for logs, history, or cached responses.

    Quick Summary: BehaviorSubject: requires initial value, replays the LAST value to new subscribers - perfect for current state (currentUser$, selectedTab$). ReplaySubject(n): replays last N values to new subscribers - useful when late subscribers need some history. BehaviorSubject is the most common for state sharing in Angular services. ReplaySubject(1) is similar to BehaviorSubject but without mandatory initial value.
    Q105:

    What is the takeUntil pattern and why is it important?

    Expert

    Answer

    takeUntil auto-unsubscribes when a notifier emits. It prevents memory leaks, especially in components with long-living subscriptions.

    Quick Summary: takeUntil pattern: create a Subject destroy$ = new Subject(). Use .pipe(takeUntil(this.destroy$)) on every subscription. In ngOnDestroy: this.destroy$.next(); this.destroy$.complete(). This automatically unsubscribes all takeUntil streams when component destroys. Angular 16+ has takeUntilDestroyed() that eliminates the manual Subject. Critical for preventing memory leaks in components with subscriptions.
    Q106:

    What is switchMap and when should you use it?

    Expert

    Answer

    switchMap cancels previous inner observables and switches to a new one. Perfect for search boxes, route params, dependent dropdowns, and avoiding race conditions.

    Quick Summary: switchMap cancels the previous inner Observable when a new outer value arrives. Perfect for search autocomplete - if user types quickly, cancel the in-flight HTTP request and start a new one. Only the latest result matters. Prevents stale results from old requests overwriting newer ones. Don't use switchMap if you need all results (use mergeMap) or ordered results (use concatMap).
    Q107:

    What is mergeMap and how is it different from switchMap?

    Expert

    Answer

    mergeMap runs all inner observables concurrently. It is ideal for batch operations or parallel API calls, unlike switchMap which cancels previous executions.

    Quick Summary: mergeMap subscribes to each inner Observable immediately as outer values arrive, running all concurrently without cancellation. Unlike switchMap (cancels previous), mergeMap keeps all in-flight. Use for parallel operations where all results are needed: upload multiple files simultaneously, process multiple items independently. Caution: no ordering guarantee, unlimited concurrency can overwhelm servers.
    Q108:

    Explain debounceTime with a real example.

    Expert

    Answer

    debounceTime delays emissions until input stabilizes. Common usage: wait for the user to stop typing before calling a search API to avoid unnecessary requests.

    Quick Summary: debounceTime delays emitting a value until N milliseconds have passed with no new values. Real example: search input - user types "angular" one letter at a time, debounceTime(300) waits until typing pauses 300ms before firing the HTTP search request. Without it, every keystroke triggers a request. Essential for rate-limiting user input events (search, autocomplete, window resize).
    Q109:

    What architecture does Angular recommend for large applications?

    Expert

    Answer

    Angular recommends:

    • Feature & core modules
    • Smart/dumb components
    • Reusable shared modules
    • Service-based data layer
    • Routing boundaries
    • State management

    This ensures scalability and clear separation of concerns.

    Quick Summary: Angular recommends feature module architecture for large apps: CoreModule (singleton services, guards, interceptors - imported once in AppModule), SharedModule (reusable components/pipes/directives - imported in feature modules), Feature Modules (domain-specific components and services). Modern approach: standalone components with functional APIs reduce the need for NgModule architecture.
    Q110:

    What is a Facade pattern in Angular and why is it used?

    Expert

    Answer

    A Facade provides a simplified API to components by hiding underlying complexity such as services, state, and API calls. It reduces coupling and improves maintainability.

    Quick Summary: Facade pattern in Angular: a service that abstracts away complex NgRx store interactions behind a simple API. Components call facade.loadUsers() instead of dispatching actions directly. The facade dispatches the action and exposes selectors as Observables. Benefits: components don't know about NgRx (easier to swap state management), simpler component code, and facades are easy to mock in tests.
    Q111:

    What is the role of the CoreModule and why must it be loaded once?

    Expert

    Answer

    CoreModule contains global singletons (services, interceptors, configs). Loading it more than once creates duplicate instances and breaks global state.

    Quick Summary: CoreModule holds app-wide singleton services (AuthService, LoggingService, HTTP interceptors) and is imported only once in AppModule. Importing it in feature modules would create duplicate service instances. Guard against multiple imports: add a constructor check that throws if the module was already loaded. Angular's providedIn: "root" mostly replaces CoreModule for services in modern Angular.
    Q112:

    Why is SharedModule used and what should it contain?

    Expert

    Answer

    SharedModule contains reusable UI pieces—components, directives, pipes. It must NOT contain stateful services to avoid duplicated instances.

    Quick Summary: SharedModule contains: commonly used components (buttons, cards, inputs), directives, pipes, and Angular modules re-exported for convenience (CommonModule, ReactiveFormsModule). Import it in any feature module that needs shared UI. SharedModule should NOT provide services (would create duplicates). Keep it lean - only add what's used in 3+ feature modules.
    Q113:

    What is State Management and why do enterprise apps need it?

    Expert

    Answer

    State management centralizes data, ensures predictable updates, reduces duplication, simplifies debugging, and enables caching and reactive UIs. Enterprises rely on it for consistency.

    Quick Summary: State management handles data that multiple components share. Without it: prop drilling, component coupling, hard to debug. Simple apps: services with BehaviorSubjects. Medium complexity: NgRx Signals or ComponentStore. Large apps with complex interactions: NgRx Store with strict unidirectional data flow. State management becomes essential when data must stay consistent across many components with complex update logic.
    Q114:

    What is NgRx and when should you use it?

    Expert

    Answer

    NgRx implements Redux principles with actions, reducers, selectors, and effects. Use it when applications have large shared state, complex flows, or need deterministic debugging.

    Quick Summary: NgRx is a reactive state management library for Angular based on Redux pattern. Use it when: multiple components share state, state changes have complex side effects, you need deterministic state updates with time-travel debugging. Overkill for simple CRUD apps. NgRx 16+ added Signal Store as a simpler alternative for local/feature state management without full Redux boilerplate.
    Q115:

    What are NgRx Effects and why are they needed?

    Expert

    Answer

    Effects handle side effects like API calls, caching, and async workflows without polluting reducers. They keep the store pure and predictable.

    Quick Summary: NgRx Effects handle async side effects (HTTP calls, navigation) triggered by actions. An Effect listens for specific actions, performs async work (HTTP request), and dispatches success or failure actions. Keeps side effects out of reducers (which must be pure functions) and components (which should only dispatch actions). Effects are testable, isolated, and handle complex async workflows cleanly.
    Q116:

    What is the purpose of HTTP Interceptors in Angular?

    Expert

    Answer

    Interceptors modify all HTTP requests/responses. They inject tokens, handle errors, retry requests, log APIs, and centralize HTTP concerns for maintainability.

    Quick Summary: HTTP Interceptors in Angular intercept all HTTP requests and responses before they reach the component code. Common uses: inject Authorization header for every request, handle 401 (unauthorized) globally by redirecting to login, show a global loading indicator, log all requests/responses, retry failed requests automatically. Register multiple interceptors - they form a chain with a defined order.
    Q117:

    What is the function of Route Guards in large Angular applications?

    Expert

    Answer

    Route Guards protect navigation, enforce security, manage unsaved changes, restrict lazy loading, and validate data before route activation.

    Quick Summary: Route Guards in large apps: CanActivate guards protect routes from unauthorized access (check auth token, roles). CanLoad prevents lazy module download for unauthorized users (saves bandwidth). Resolve pre-fetches data so the component has data on initialization (no loading states in component). CanDeactivate warns users about unsaved form data before navigating away. Guards are essential for security and UX in large apps.
    Q118:

    Explain Lazy Loading and how it impacts Angular architecture.

    Expert

    Answer

    Lazy loading loads feature modules only when accessed. This reduces initial bundle size, improves performance, and enforces clean module boundaries in large systems.

    Quick Summary: Lazy loading splits the app into feature bundles loaded on demand. Architecture impact: each lazy feature module has its own providers, routes, and components. The initial bundle stays small. When a user navigates to /admin, the admin bundle downloads. Combine with preloading to download lazy modules in the background after initial load. Essential for large apps where every KB of initial load matters.
    Q119:

    Why is Component Communication pattern crucial in Angular architecture?

    Expert

    Answer

    Angular apps rely on clear communication patterns—Inputs, Outputs, services, Subjects, and facades. These prevent coupling, simplify flows, and support scalable UI structure.

    Quick Summary: Component communication patterns: Parent to Child via @Input. Child to Parent via @Output EventEmitter. Sibling components via a shared service with BehaviorSubject. Distant components via NgRx Store or service state. Avoid: directly accessing child component instances (tight coupling). Good communication patterns keep components decoupled and independently testable.
    Q120:

    How do you design an Angular application for long-term maintainability?

    Expert

    Answer

    Use modular structure, proper state management, facades, smart/dumb components, DRY architecture, consistent naming, and unit-tested services/components for long-term maintainability.

    Quick Summary: Angular maintainability: apply consistent architecture (Core/Shared/Feature modules or standalone components), use smart/dumb component pattern, keep components small (split when >300 lines), lazy load all feature routes, use TypeScript strictly (strict mode), write tests for services and critical components, document with JSDoc, and enforce standards via ESLint + Angular-specific lint rules.

    Curated Sets for Angular

    No curated sets yet. Group questions into collections from the admin panel to feature them here.

    Ready to level up? Start Practice