Angular

1. What is Angular & Meaning

Beginner
Angular is a complete, all-in-one web application framework developed and maintained by Google. It is built with TypeScript and designed specifically for creating fast, scalable Single Page Applications (SPAs).
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of Angular like a factory-assembled luxury commercial aircraft: complete with flight controls, radars, emergency exits, and navigation systems built right into the airframe!
  • What is Angular? A powerful TypeScript-based frontend framework created by Google to build modern web applications.
  • Angular vs AngularJS: AngularJS (version 1.x) was based on JavaScript and is now retired. Modern Angular (version 2 and above, now Angular 17+) is completely rewritten in TypeScript.
  • Batteries Included: Unlike libraries that need third-party tools, Angular comes with everything built-in: routing, forms, HTTP client, and testing.
  • Real-Life Analogy: If React is a powerful car engine where you buy the wheels and doors separately, Angular is a luxury car factory that gives you the complete assembled vehicle ready to drive.
💻 1. Your First Angular Component
Output Terminal Standard Output
Click "▶ Run" to execute program output.
🧠 Topic 1 Practice Quiz (4 Questions)
Q1. Who developed and maintains the Angular framework?
✅ Correct Answer: Option C
Explanation: (Angular was created and is actively maintained by Google and a global open-source community.)
Q2. Which programming language is core to modern Angular development?
✅ Correct Answer: Option A
Explanation: (Angular is built from the ground up with TypeScript, offering static typing and strong tooling.)
Q3. What is the key difference between AngularJS and modern Angular?
✅ Correct Answer: Option D
Explanation: (AngularJS (1.x) was JavaScript-based with controllers. Modern Angular (2+) is TypeScript-based with components.)
Q4. Why is Angular called a 'Batteries-Included' framework?
✅ Correct Answer: Option B
Explanation: (Angular is an opinionated framework that provides standard solutions for routing, HTTP, and forms out of the box.)
Topic 1 Interview Questions & Answers
Q1: What is Angular and what are its key architectural building blocks? ▼
Answer: Angular is a TypeScript-based framework by Google for building scalable web apps. Its key building blocks are: Components (UI + logic), Templates (HTML), Directives (DOM manipulation), Services (reusable business logic), and Dependency Injection.
Q2: How does Angular differ from React? ▼
Answer: React is a UI library that gives developers flexibility to pick routing and form libraries. Angular is a complete framework with official routing, forms, HTTP client, and RxJS integration out of the box.
Q3: What are Standalone Components in modern Angular? ▼
Answer: Standalone Components (introduced in Angular 14/15) eliminate the need for NgModule. Components specify their own dependencies directly via imports: [CommonModule, RouterLink], reducing boilerplate.
Q4: What is TypeScript and why does Angular use it? ▼
Answer: TypeScript is a strongly typed superset of JavaScript developed by Microsoft. Angular uses it because compile-time type checking, interfaces, and decorators help catch bugs early in large enterprise applications.

2. Why Angular is used, Features & Applications

Beginner
Understand why Fortune 500 banks, healthcare corporations, and enterprise tech leaders choose Angular for large, mission-critical applications.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of Angular's Enterprise Features like building skyscraper headquarters for Fortune 500 banks that need strict security and reliability!
  • Two-Way Data Binding: Synchronizes data between your TypeScript code and your HTML template automatically in real-time.
  • Dependency Injection (DI): A design pattern where Angular provides services to components automatically, making code modular and testable.
  • Cross-Platform Support: Build web apps, Progressive Web Apps (PWAs), mobile apps with Ionic/Capacitor, and desktop apps with Electron.
  • Enterprise Adoption: Used by Google, Microsoft, Forbes, PayPal, and Deutsche Bank for security, consistency, and long-term support.
💻 2. Two-Way Data Binding Preview
Output Terminal Standard Output
Click "▶ Run" to execute program output.
🧠 Topic 2 Practice Quiz (4 Questions)
Q1. Which company originally created and uses Angular extensively across its products?
✅ Correct Answer: Option B
Explanation: (Google created Angular and uses it for major internal and external platforms including Google Cloud Console.)
Q2. What is Dependency Injection in Angular?
✅ Correct Answer: Option D
Explanation: (Dependency Injection (DI) allows classes to receive dependencies from external sources rather than creating them manually.)
Q3. Why do large enterprises favor Angular over smaller tools?
✅ Correct Answer: Option A
Explanation: (Enterprise teams value Angular's consistent standards, strict TypeScript architecture, and built-in enterprise tooling.)
Q4. Which syntax represents Two-Way Data Binding in Angular?
✅ Correct Answer: Option C
Explanation: ([()] combines property binding [] and event binding () - commonly remembered as 'banana in a box'.)
Topic 2 Interview Questions & Answers
Q1: What are the core features of the Angular framework? ▼
Answer: 1. Component-based architecture. 2. Powerful CLI. 3. Hierarchical Dependency Injection. 4. Declarative Two-Way Data Binding. 5. Built-in routing and forms. 6. Ahead-of-Time (AOT) compilation.
Q2: What is Ahead-of-Time (AOT) compilation in Angular? ▼
Answer: AOT compiles Angular HTML and TypeScript code into efficient JavaScript during the build process, before the browser downloads it. This results in faster rendering and early detection of template errors.
Q3: How does Angular prevent Cross-Site Scripting (XSS) attacks? ▼
Answer: Angular treats all values as untrusted by default. When values are inserted into templates via interpolation or property binding, Angular automatically sanitizes them using the DomSanitizer.
Q4: What types of applications are best suited for Angular? ▼
Answer: Complex enterprise Single Page Applications (SPAs), financial dashboards, customer portals, content management systems (CMS), and Progressive Web Apps requiring strict architecture and scalability.

3. Node.js & npm Setup

Beginner
Before writing any Angular code, your computer needs Node.js and npm to download dependencies and run the development compiler.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of Node.js and npm like the cargo container ships and cranes supplying construction materials to the construction site!
  • Node.js: An open-source runtime environment that executes JavaScript code on your computer outside the browser.
  • npm (Node Package Manager): The world's largest software registry. It installs Angular libraries and CLI tools.
  • Verifying Installation: Open your terminal or command prompt and run: 'node -v' and 'npm -v'.
  • LTS Version: Always install the Long Term Support (LTS) version of Node.js for guaranteed stability.
💻 3. Checking Environment Versions
Output Terminal Standard Output
Click "▶ Run" to execute program output.
🧠 Topic 3 Practice Quiz (4 Questions)
Q1. What is Node.js?
✅ Correct Answer: Option D
Explanation: (Node.js allows JavaScript to run on servers and local developer machines.)
Q2. What does 'npm' stand for?
✅ Correct Answer: Option B
Explanation: (npm stands for Node Package Manager, used to download open-source libraries.)
Q3. Which terminal command checks your installed Node.js version?
✅ Correct Answer: Option C
Explanation: ('node -v' or 'node --version' prints the currently active Node version.)
Q4. Which command installs the Angular CLI globally across your entire computer?
✅ Correct Answer: Option A
Explanation: (The '-g' flag tells npm to install @angular/cli globally so the 'ng' command is accessible in any terminal.)
Topic 3 Interview Questions & Answers
Q1: Why does Angular need Node.js if Angular runs in the user's browser? ▼
Answer: Angular itself runs in the browser, but Node.js is needed during development to run the Angular CLI, compile TypeScript into JavaScript, bundle assets, and run the local development server.
Q2: What is the difference between package.json and package-lock.json? ▼
Answer: package.json lists the general dependency version ranges (e.g. ^17.0.0). package-lock.json locks down the exact version, sub-dependencies, and integrity hashes to ensure identical installs across all team members.
Q3: What is npx and how does it differ from npm? ▼
Answer: npm is a package manager used to install packages. npx is a package runner that lets you execute an npm package directly without installing it globally (e.g. npx @angular/cli new my-app).
Q4: What does the 'npm install' command do when cloned in a new repository? ▼
Answer: It reads the package.json file and downloads all listed dependencies into the local 'node_modules/' directory.

4. Angular CLI & Project Commands

Beginner
The Angular Command Line Interface (CLI) is a powerful tool to initialize, develop, scaffold, and maintain Angular applications directly from the terminal.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of Angular CLI like a voice-activated 3D building printer: typing ng generate component prints out complete scaffolding in 1 second!
  • Create a New Project: Run 'ng new my-app' to generate a full-featured project structure automatically.
  • Start Dev Server: Run 'ng serve --open' (or 'ng s -o') to start the server at http://localhost:4200 and open your browser.
  • Generate Code (Scaffolding): Run 'ng generate component my-component' (or 'ng g c my-component') to create component files automatically.
  • Build for Production: Run 'ng build' to produce an optimized, minified bundle inside the dist/ folder.
💻 4. Key Angular CLI Commands Reference
Output Terminal Standard Output
Click "▶ Run" to execute program output.
🧠 Topic 4 Practice Quiz (4 Questions)
Q1. Which command creates a brand-new Angular project using the CLI?
✅ Correct Answer: Option A
Explanation: ('ng new <project-name>' generates a complete Angular workspace with all starter files.)
Q2. Which command runs your Angular app locally in the browser?
✅ Correct Answer: Option C
Explanation: ('ng serve' builds and serves the application locally, with live reload on changes.)
Q3. What is the shortcut command to generate a new component in Angular CLI?
✅ Correct Answer: Option B
Explanation: ('ng g c <name>' is the official shorthand for 'ng generate component <name>'.)
Q4. What is the default port used by 'ng serve'?
✅ Correct Answer: Option D
Explanation: (Angular CLI serves applications on port 4200 by default (http://localhost:4200).)
Topic 4 Interview Questions & Answers
Q1: What are the major advantages of using Angular CLI? ▼
Answer: The CLI standardizes project setup, automates boilerplate file generation, enforces best practices, handles TypeScript compilation and bundler configuration, and automates testing and production builds.
Q2: What files are automatically created when you run 'ng g c my-card'? ▼
Answer: Four files: 1. my-card.component.ts (logic), 2. my-card.component.html (template), 3. my-card.component.css (styles), and 4. my-card.component.spec.ts (unit test).
Q3: What is the purpose of the 'angular.json' file? ▼
Answer: angular.json is the CLI configuration file for your entire workspace. It controls build targets, asset paths, global stylesheets, scripts, development server options, and test runners.
Q4: How does the '--dry-run' flag help when using Angular CLI? ▼
Answer: Adding '--dry-run' (or '-d') simulates the command and shows what files would be created or modified without actually writing any changes to your hard drive.

5. src & app Folders

Beginner
Explore the internal architecture of an Angular project. Learn what each folder does, where your code lives, and how the app boots up.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of the src/app folder like the main control room of a nuclear submarine where all operations and navigation screens reside!
  • src/ folder: The source code folder where 99% of your development work happens.
  • src/main.ts: The application entry point that bootstraps the root Angular component into the browser.
  • src/index.html: The main HTML page hosting the <app-root> selector.
  • src/app/ folder: Contains your components, services, pipes, and application modules.
💻 5. Bootstrapping Angular in main.ts
Output Terminal Standard Output
Click "▶ Run" to execute program output.
🧠 Topic 5 Practice Quiz (4 Questions)
Q1. Which file is the main entry point that boots up an Angular application?
✅ Correct Answer: Option C
Explanation: (src/main.ts executes bootstrapApplication() to launch the Angular app in the browser.)
Q2. What HTML tag in src/index.html is replaced by the root component?
✅ Correct Answer: Option D
Explanation: (index.html contains <app-root></app-root>, which Angular replaces with the compiled AppComponent template.)
Q3. Where should images, icons, and static assets be placed in an Angular project?
✅ Correct Answer: Option B
Explanation: (The 'src/assets/' directory is the designated location for static files (images, fonts, mock JSON).)
Q4. Where does your component and service code live?
✅ Correct Answer: Option A
Explanation: (src/app/ is where all application components, pages, services, and logic are stored.)
Topic 5 Interview Questions & Answers
Q1: Explain the startup flow of an Angular application. ▼
Answer: 1. The browser requests index.html. 2. Script tags load the bundled JavaScript (main.ts). 3. main.ts calls bootstrapApplication(AppComponent). 4. Angular finds the selector <app-root> in index.html and renders the AppComponent.
Q2: What is the difference between standalone bootstrapApplication() and the legacy bootstrapModule()? ▼
Answer: bootstrapModule(AppModule) is the legacy NgModule approach. In modern Angular (v15+), bootstrapApplication(AppComponent) directly mounts standalone components without needing an AppModule class.
Q3: What is the purpose of the 'app.config.ts' file in modern Angular? ▼
Answer: app.config.ts provides application-wide providers (like provideRouter(routes), provideHttpClient(), and provideAnimations()) for standalone apps without an NgModule.
Q4: What does the tsconfig.json file do in an Angular project? ▼
Answer: It configures the TypeScript compiler (target ECMAScript version, module resolution, strict type checking flags, and path aliases).

6. Component Files & Project Configs

Beginner
Every Angular component consists of four closely coordinated files: TypeScript logic (.ts), HTML template (.html), CSS styles (.css), and Unit tests (.spec.ts).
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of Component Architecture like a modular kitchen suite: stainless steel counters, induction cookers, and dishwashers fitting together seamlessly!
  • name.component.ts: The TypeScript class holding data properties and event handler methods.
  • name.component.html: The HTML template displaying data to users.
  • name.component.css: Styles encapsulated strictly to this specific component.
  • name.component.spec.ts: Automated unit tests written with Jasmine/Karma.
💻 6. Anatomy of an Angular Component Class
Output Terminal Standard Output
Click "▶ Run" to execute program output.
🧠 Topic 6 Practice Quiz (4 Questions)
Q1. How many files does Angular CLI generate by default for a new component?
✅ Correct Answer: Option B
Explanation: (Angular CLI generates four files: TypeScript logic, HTML template, CSS styling, and spec unit test.)
Q2. What is the purpose of the '.spec.ts' file in an Angular component?
✅ Correct Answer: Option A
Explanation: (Files ending in '.spec.ts' are unit test specifications executed by the test runner.)
Q3. What does View Encapsulation do in Angular component CSS?
✅ Correct Answer: Option C
Explanation: (Angular encapsulates component styles by default (Emulated) so rules do not affect other components on the page.)
Q4. Which decorator marks a TypeScript class as an Angular component?
✅ Correct Answer: Option D
Explanation: (The @Component decorator provides metadata (selector, template, styles) telling Angular the class is a component.)
Topic 6 Interview Questions & Answers
Q1: What are the three types of View Encapsulation in Angular? ▼
Answer: 1. Emulated (default): Angular adds unique attributes to component elements so styles don't leak. 2. ShadowDom: Uses native browser Shadow DOM. 3. None: Styles are global and affect the entire application.
Q2: Can you write inline HTML and CSS inside the @Component decorator? ▼
Answer: Yes. You can use 'template: `<div>...</div>`' instead of templateUrl, and 'styles: [`h1 { color: red; }`]' instead of styleUrls.
Q3: What is the difference between a Component and a Directive in Angular? ▼
Answer: A Component is a directive with a template (UI). Directives (like *ngIf or [ngClass]) add behavior or transform existing DOM elements without their own separate templates.
Q4: Why is separation of concerns important in the 4-file component structure? ▼
Answer: It separates presentation (HTML) from business logic (TypeScript), styling (CSS), and verification (Tests), making large enterprise applications easier to maintain and test.

7. Variables & Primitive Data Types in TypeScript

Beginner
TypeScript brings static typing to JavaScript. In this topic, learn the core primitive data types (string, number, boolean, any, void) that make Angular code robust and bug-free.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of TypeScript Types like clearly labeled sorting bins for nuts and bolts, preventing square pegs from entering round holes at compile time!
  • string: Textual data: let name: string = 'Kiran';
  • number: Integers and floating-point numbers: let age: number = 25;
  • boolean: True or false values: let isStudent: boolean = true;
  • any & union types: any disables type checking (use sparingly!). Union types allow multiple types: let id: string | number = 101;
💻 7. Declaring Typed Variables in TypeScript
Output Terminal Standard Output
Click "▶ Run" to execute program output.
🧠 Topic 7 Practice Quiz (4 Questions)
Q1. Which TypeScript type represents true or false values?
✅ Correct Answer: Option D
Explanation: (In TypeScript, boolean is the official type representing true or false.)
Q2. What is a Union Type in TypeScript?
✅ Correct Answer: Option C
Explanation: (Union types use the pipe symbol (|) to allow a value to be one of multiple specified types.)
Q3. Why should you avoid using the 'any' type in TypeScript?
✅ Correct Answer: Option A
Explanation: ('any' opts out of type safety, preventing TypeScript from detecting type mismatches and bugs.)
Q4. How do you declare a typed array of numbers in TypeScript?
✅ Correct Answer: Option B
Explanation: ('number[]' (or Array<number>) declares an array containing only numeric values.)
Topic 7 Interview Questions & Answers
Q1: What is type inference in TypeScript? ▼
Answer: Type inference is when TypeScript automatically guesses and assigns a type based on the initial assigned value. For example, let x = 5; infers x as type 'number' without explicit annotation.
Q2: What is the difference between 'null' and 'undefined' in TypeScript? ▼
Answer: 'undefined' means a variable has been declared but has not yet been assigned a value. 'null' is an intentional assignment representing the explicit absence of any object value.
Q3: What is the 'unknown' type and how is it safer than 'any'? ▼
Answer: 'unknown' is the type-safe counterpart of 'any'. You can assign any value to an unknown variable, but you cannot call methods or access properties on it until you perform type checking (narrowing).
Q4: What does the 'readonly' modifier do in TypeScript classes? ▼
Answer: The 'readonly' modifier prevents a property from being reassigned outside the constructor function.

8. Functions, Classes & Interfaces in TypeScript

Beginner
Interfaces define custom data contracts, classes encapsulate state and methods, and typed functions ensure safe data exchange across your Angular codebase.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of TypeScript Interfaces like architectural construction contracts: guaranteeing every building contractor fulfills the required specs!
  • Interfaces: Define the shape of data: interface User { id: number; name: string; email: string; }
  • Classes: Blueprints for objects that implement interfaces and contain constructors and methods.
  • Typed Functions: Functions with explicit parameter types and return types: add(a: number, b: number): number { return a + b; }
  • Access Modifiers: public (default, accessible anywhere), private (accessible only inside this class), and protected (accessible in class and subclasses).
💻 8. Defining Interfaces & Classes
Output Terminal Standard Output
Click "▶ Run" to execute program output.
🧠 Topic 8 Practice Quiz (4 Questions)
Q1. What is an Interface in TypeScript?
✅ Correct Answer: Option A
Explanation: (An interface defines properties and types an object must have, without implementing logic.)
Q2. How do you mark a property as optional in a TypeScript interface?
✅ Correct Answer: Option B
Explanation: (The '?' symbol indicates that the property is optional and can be omitted.)
Q3. Which access modifier restricts access to a property strictly inside its own class?
✅ Correct Answer: Option D
Explanation: ('private' ensures the property or method can only be accessed from within that specific class.)
Q4. What does a function return if its return type is marked as 'void'?
✅ Correct Answer: Option C
Explanation: ('void' indicates that a function executes logic but does not return any value.)
Topic 8 Interview Questions & Answers
Q1: What is the difference between an Interface and a Type alias in TypeScript? ▼
Answer: Interfaces are extendable (declaration merging, extends) and primarily used for defining object shapes. Type aliases can also define union types, primitives, and tuples, but cannot be reopened to add new properties.
Q2: What are TypeScript Generics and why are they used in Angular? ▼
Answer: Generics allow you to create reusable components/functions that work with any data type while maintaining type safety (e.g., Observable<User[]> or Array<T>).
Q3: Does TypeScript interfaces exist in the compiled JavaScript bundle? ▼
Answer: No. Interfaces are purely compile-time constructs used by TypeScript for type checking. They are completely erased during compilation and add zero bytes to the JavaScript bundle.
Q4: What is parameter property shorthand in TypeScript class constructors? ▼
Answer: Writing 'constructor(private http: HttpClient) {}' automatically declares the 'http' member variable on the class and assigns the injected value, eliminating boilerplate.

9. What is a Component & Creation

Beginner
Components are the fundamental UI building blocks of Angular applications. Every Angular screen is a tree of nested components.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of an Angular Component like a modern television studio set with a camera view (HTML template), lighting design (CSS), and a director's cue card (TypeScript)!
  • Component Anatomy: Consists of a TypeScript class decorated with @Component, containing a selector, HTML template, and CSS styles.
  • The Selector: A custom HTML tag (e.g. 'app-header') that tells Angular where to place the component in the DOM.
  • Creating via CLI: Run 'ng g c components/navbar' to generate a new component in seconds.
  • Standalone Components: Modern Angular components set 'standalone: true' so they can be imported directly without NgModule.
💻 9. Defining a Complete Standalone Component
Output Terminal Standard Output
Click "▶ Run" to execute program output.
🧠 Topic 9 Practice Quiz (4 Questions)
Q1. What is an Angular Component?
✅ Correct Answer: Option C
Explanation: (Components control a patch of screen called a view, combining TypeScript logic with an HTML template.)
Q2. What does the 'selector' property inside @Component define?
✅ Correct Answer: Option B
Explanation: (The selector defines the custom HTML tag (like <app-navbar>) that represents the component.)
Q3. What flag marks a component as a modern Standalone Component in Angular?
✅ Correct Answer: Option A
Explanation: ('standalone: true' inside the @Component decorator marks it as standalone.)
Q4. How do you render a child component <app-navbar> inside a parent component?
✅ Correct Answer: Option D
Explanation: (For standalone components, import the child component in the parent's 'imports: [...]' array and use its selector tag.)
Topic 9 Interview Questions & Answers
Q1: What is the metadata inside the @Component decorator? ▼
Answer: It includes: selector (custom tag name), standalone (boolean), imports (dependencies), template / templateUrl (HTML markup), and styles / styleUrls (component CSS).
Q2: What is the difference between inline templates and external template files? ▼
Answer: Inline templates ('template: `...`') keep HTML inside the .ts file, ideal for small components under 20 lines. External templates ('templateUrl: './app.html'') keep HTML in a separate file, better for large templates.
Q3: How does Angular establish a component hierarchy tree? ▼
Answer: The root component (<app-root>) contains child components (like <app-navbar>, <app-sidebar>), which can in turn contain grandchild components, forming a hierarchical component tree.
Q4: What is change detection in Angular components? ▼
Answer: Change detection is the mechanism by which Angular synchronizes the component's internal TypeScript state with the DOM template whenever events, timers, or HTTP requests finish.

10. Component Structure & Properties

Beginner
Dive deep into class properties, public vs private fields, and data initialization in Angular components.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of Component Properties like the digital dials and switches on a dashboard!
  • Class Properties: Variables defined on the class that store component state.
  • Constructor vs ngOnInit: Constructors are for simple dependency injection. Complex initialization (like API calls) should happen in ngOnInit().
  • Template Accessibility: Properties bound in the HTML template must be 'public' (default) so the template can read them.
  • Computed Properties (Getters): Use JavaScript get propertyName() to return calculated values dynamically.
💻 10. Component Properties and Getters
Output Terminal Standard Output
Click "▶ Run" to execute program output.
🧠 Topic 10 Practice Quiz (4 Questions)
Q1. Why must component properties used in HTML templates be public?
✅ Correct Answer: Option B
Explanation: (Templates are compiled into separate view classes that must access public properties of the component.)
Q2. What is the recommended place to fetch initial data for an Angular component?
✅ Correct Answer: Option C
Explanation: (ngOnInit() is the official lifecycle hook for component initialization and data fetching.)
Q3. What is a TypeScript getter method (e.g. get totalPrice())?
✅ Correct Answer: Option D
Explanation: (Getters compute derived state dynamically when read, behaving like read-only properties.)
Q4. What is the primary role of a component's constructor in Angular?
✅ Correct Answer: Option A
Explanation: (Constructors in Angular should be lightweight and primarily used for injecting dependencies.)
Topic 10 Interview Questions & Answers
Q1: What is the difference between constructor() and ngOnInit()? ▼
Answer: constructor() is a native TypeScript feature called when the class instance is created, used for DI. ngOnInit() is an Angular lifecycle hook called after Angular sets up input properties and child bindings, making it the right place for initialization logic.
Q2: Can you pass parameters to a getter in TypeScript? ▼
Answer: No. Getters cannot take parameters. If you need parameters, use a standard method: calculateDiscount(price, percent).
Q3: How does Angular detect changes to component properties? ▼
Answer: Historically via Zone.js, which patches async browser APIs (click, setTimeout, HTTP) to notify Angular to run change detection. In modern Angular 16+, Signals provide fine-grained reactivity without Zone.js.
Q4: What happens if a property accessed in a template is undefined? ▼
Answer: If accessing nested properties (e.g. user.address.city) where user or address is undefined, it throws a TypeError. Use the safe navigation operator (user?.address?.city) to prevent crashes.

11. What is a Template & HTML in Angular

Beginner
An Angular template is dynamic HTML that combines standard HTML tags with Angular expressions, bindings, and directives to render dynamic user interfaces.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of Angular Templates like a fill-in-the-blank diploma certificate waiting for student names to be printed dynamically!
  • Angular Template Syntax: Standard HTML enhanced with {{ }} interpolation, [] property binding, and () event binding.
  • Template Expressions: JavaScript-like snippets inside templates that evaluate to a value (e.g. {{ 1 + 1 }} or {{ user.name }}).
  • Template Statements: Methods called in response to user events (e.g. (click)='saveData()').
  • Safe Navigation Operator (?.): Prevents null-pointer exceptions when accessing nested object properties: {{ user?.profile?.avatar }}.
💻 11. Dynamic Template Expressions and Safe Navigation
Output Terminal Standard Output
Click "▶ Run" to execute program output.
🧠 Topic 11 Practice Quiz (4 Questions)
Q1. What is the Safe Navigation Operator in Angular templates?
✅ Correct Answer: Option D
Explanation: (The '?.' operator guards against null or undefined values in nested property paths.)
Q2. Can you declare new JavaScript variables (like 'var x = 10;') directly inside an Angular template?
✅ Correct Answer: Option A
Explanation: (Template expressions must be expressions (producing a value), not statements (assignments or variable declarations).)
Q3. What happens if a template expression references a non-existent property without safe navigation?
✅ Correct Answer: Option B
Explanation: (Accessing deep properties on null/undefined causes a runtime TypeError, which is why '?.' is recommended.)
Q4. What HTML elements can be used inside an Angular template?
✅ Correct Answer: Option C
Explanation: (Angular templates support all valid HTML5 elements along with custom component tags and directives.)
Topic 11 Interview Questions & Answers
Q1: What are the rules and restrictions for Angular template expressions? ▼
Answer: Template expressions cannot: 1. Use assignments (=, +=). 2. Use 'new' operator. 3. Chain expressions with semicolons. 4. Access global namespace objects directly (window, document, console).
Q2: How can you access the browser console.log inside an Angular template? ▼
Answer: By default you cannot write console.log() in templates. You must expose a method on your component class: log(msg: any) { console.log(msg); } and call that method from the template.
Q3: What is an <ng-container> and why is it useful in templates? ▼
Answer: <ng-container> is a logical grouping element that does NOT render any actual node into the DOM. It is useful for applying directives like *ngIf or *ngFor without creating redundant wrapper <div> tags.
Q4: What is an <ng-template> in Angular? ▼
Answer: <ng-template> defines a template fragment that is NOT rendered by default. It is rendered conditionally using *ngIf else, ngTemplateOutlet, or view containers.

12. Interpolation {{ }} & Template Expressions

Beginner
Interpolation is the most common way to display data in Angular. Wrap any TypeScript property or expression in double curly braces {{ }} to show it in HTML.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of Interpolation ({{ }}) like a neon digital scoreboard that updates the stadium score as soon as a goal is scored!
  • Syntax: Double curly braces: <p>{{ message }}</p>.
  • String Conversion: Angular evaluates whatever is inside the braces, converts it to a string, and inserts it into the HTML.
  • Calling Methods: You can call component methods: {{ calculateTotal() }}, but avoid heavy computations here as it runs on every change detection cycle!
  • Ternary in Interpolation: Use inline ternaries for clean display: {{ isOnline ? 'Active' : 'Offline' }}.
💻 12. Displaying Data with Interpolation
Output Terminal Standard Output
Click "▶ Run" to execute program output.
🧠 Topic 12 Practice Quiz (4 Questions)
Q1. What syntax represents string interpolation in Angular templates?
✅ Correct Answer: Option A
Explanation: (Angular uses double curly braces {{ }} for string interpolation.)
Q2. What does Angular do with the result of an expression inside {{ }}?
✅ Correct Answer: Option D
Explanation: (Angular evaluates the expression, calls toString() on the result, and injects it into the DOM text node.)
Q3. Why should you avoid calling expensive or heavy methods inside {{ }}?
✅ Correct Answer: Option C
Explanation: (Interpolated methods run on every change detection pass. Use pure pipes or pre-calculated properties instead for performance.)
Q4. Can you write arithmetic calculations inside {{ }} (e.g. {{ 50 + 25 }})?
✅ Correct Answer: Option B
Explanation: (Simple math expressions like addition, subtraction, and multiplication are fully supported inside interpolation.)
Topic 12 Interview Questions & Answers
Q1: How does interpolation {{ value }} relate to property binding [innerText]='value'? ▼
Answer: Interpolation is actually syntactic sugar for property binding. Under the hood, Angular translates

{{ message }}

into property binding to the DOM element's textContent/innerText property.
Q2: What is the performance difference between a getter and a pure pipe? ▼
Answer: A getter in a template runs on every change detection tick, even if data hasn't changed. A pure pipe only recalculates when its input arguments change by reference, saving CPU cycles.
Q3: Can interpolation be used on HTML element attributes (e.g. <img src='{{ imgUrl }}'>)? ▼
Answer: Yes, Angular allows this, but canonical property binding <img [src]='imgUrl'> is preferred by Angular style guides for cleaner syntax.
Q4: How does Angular prevent script injection when rendering interpolated HTML strings? ▼
Answer: Angular escapes raw HTML strings by default so <script>alert()</script> is rendered harmlessly as plain text. To render actual HTML, you must bind to [innerHTML] and use DomSanitizer.

13. Property & Event Binding

Beginner
Data in Angular flows two ways: Property Binding sends data from TypeScript to HTML, and Event Binding sends user events from HTML to TypeScript.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of Event Binding like tapping a car horn on the steering wheel: sound immediately blares outward!
  • Property Binding [property]: Passes data from component to an HTML attribute or child component: <button [disabled]='isSubmitting'>.
  • Event Binding (event): Listens for user actions (clicks, keystrokes) and triggers methods: <button (click)='onSave()'>.
  • Passing Event Payload ($event): Pass the native DOM event object using $event: <input (input)='onType($event)'>.
  • Direction Summary: [ ] = Component to DOM. ( ) = DOM to Component.
💻 13. Property & Event Binding in Action
Output Terminal Standard Output
Click "▶ Run" to execute program output.
🧠 Topic 13 Practice Quiz (4 Questions)
Q1. Which syntax represents Property Binding in Angular?
✅ Correct Answer: Option C
Explanation: (Square brackets [] bind data from component TypeScript to a DOM element property.)
Q2. Which syntax represents Event Binding in Angular?
✅ Correct Answer: Option A
Explanation: (Parentheses () listen for events (like click, input, submit) emitted by the DOM.)
Q3. What special Angular keyword passes the native browser event object to a method?
✅ Correct Answer: Option D
Explanation: ('$event' is Angular's reserved keyword used in event bindings to pass the event payload.)
Q4. What is the key difference between HTML attributes and DOM properties?
✅ Correct Answer: Option B
Explanation: (Attributes are defined by HTML to initialize properties. Property binding in Angular targets live DOM properties.)
Topic 13 Interview Questions & Answers
Q1: Why does Angular bind to DOM properties instead of HTML attributes? ▼
Answer: HTML attributes only initialize values and cannot change dynamically. DOM properties represent the live, mutable state of elements in browser memory, which is what Angular needs to keep UI synchronized.
Q2: What is Event Filtering in Angular (e.g. (keydown.enter))? ▼
Answer: Angular supports key event pseudo-names: (keydown.enter)='save()' only executes when the Enter key is pressed, eliminating manual keyCode checking inside the method.
Q3: Can you create custom events in Angular? ▼
Answer: Yes. Child components use @Output() decorated properties with EventEmitter to emit custom events that parents listen to via standard event binding: (customEvent)='handle($event)'.
Q4: What is the difference between [class.active]='isActive' and [ngClass]? ▼
Answer: [class.active] toggles a single class based on a boolean. [ngClass] can toggle multiple classes simultaneously using objects ({ 'active': true, 'disabled': false }), strings, or arrays.

14. Two-Way Data Binding [(ngModel)]

Beginner
Two-way data binding gives your app a direct two-way highway between component TypeScript properties and HTML input fields using the famous 'banana-in-a-box' syntax [(ngModel)].
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of Two-Way Binding ([(ngModel)]) like a two-way walkie-talkie: whatever you whisper into one end instantly echoes out the other!
  • What is Two-Way Binding? Typing in an input updates the TypeScript variable instantly; changing the variable in TypeScript updates the input box instantly.
  • The Banana-in-a-Box Syntax: [()] - Square brackets outside, parentheses inside: [(ngModel)]='username'.
  • Requires FormsModule: To use [(ngModel)], you MUST import 'FormsModule' from '@angular/forms' in your standalone component imports.
  • Deconstructed Syntax: [(ngModel)]='text' is exact equivalent of: [ngModel]='text' (ngModelChange)='text = $event'.
💻 14. Real-Time Two-Way Binding with FormsModule
Output Terminal Standard Output
Click "▶ Run" to execute program output.
🧠 Topic 14 Practice Quiz (4 Questions)
Q1. What module must be imported to use [(ngModel)] in Angular?
✅ Correct Answer: Option B
Explanation: ([(ngModel)] is part of FormsModule, which must be imported to enable two-way form bindings.)
Q2. How is the syntax [(ngModel)] often remembered by Angular developers?
✅ Correct Answer: Option D
Explanation: (The syntax [()] looks like a banana inside a box.)
Q3. What happens when the user types in an input with [(ngModel)]='city'?
✅ Correct Answer: Option A
Explanation: (Two-way binding synchronizes the user's keystrokes immediately to the bound TypeScript property.)
Q4. Which two bindings make up two-way data binding under the hood?
✅ Correct Answer: Option C
Explanation: ([(ngModel)] combines [ngModel] for setting the value and (ngModelChange) for listening to updates.)
Topic 14 Interview Questions & Answers
Q1: How does [(ngModel)] work behind the scenes? ▼
Answer: It is syntactic sugar for property binding and event binding combined: <input [ngModel]='val' (ngModelChange)='val = $event'>. ngModel sets the value property, and ngModelChange listens to input events to update the model.
Q2: When using [(ngModel)] inside an HTML <form>, what attribute is mandatory? ▼
Answer: The 'name' attribute is mandatory (e.g. <input [(ngModel)]='user' name='username'>) so Angular can register the control with the parent form group.
Q3: Can you create your own custom two-way data binding on child components? ▼
Answer: Yes. By creating an @Input() x property and an @Output() xChange = new EventEmitter() property following the 'Property' and 'PropertyChange' naming pattern, parents can use [(x)]='parentVal'.
Q4: Why do some enterprise teams prefer Reactive Forms over [(ngModel)]? ▼
Answer: Reactive Forms are synchronous, immutably structured, provide more powerful validation APIs, and make unit testing easier without relying on template rendering.

15. *ngIf Conditional Directive

Beginner
*ngIf is a structural directive that conditionally adds or completely removes elements from the DOM based on a boolean condition.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of *ngIf like a theater stage curtain: opening when the actor walks on stage and closing when they exit!
  • Structural Directive (*): The asterisk (*) indicates that the directive modifies the structure of the DOM (adding or destroying elements).
  • Syntax: <div *ngIf='isLoggedIn'>Welcome!</div>
  • else Template Block: Use an <ng-template #loggedOut> block to render fallback markup: <div *ngIf='isLoggedIn; else loggedOut'>.
  • *ngIf vs [hidden]: *ngIf completely removes the element from the DOM (saving memory and lifecycle), whereas [hidden] only hides it with CSS display:none.
💻 15. Conditional DOM with *ngIf and else Block
Output Terminal Standard Output
Click "▶ Run" to execute program output.
🧠 Topic 15 Practice Quiz (4 Questions)
Q1. What does the asterisk (*) prefix in *ngIf signify?
✅ Correct Answer: Option D
Explanation: (The asterisk (*) denotes structural directives that alter the DOM tree structure.)
Q2. What is the key performance difference between *ngIf and the HTML [hidden] attribute?
✅ Correct Answer: Option B
Explanation: (*ngIf removes elements entirely, freeing memory, destroying event listeners, and halting component lifecycles.)
Q3. How do you specify an 'else' fallback template for *ngIf?
✅ Correct Answer: Option C
Explanation: (Angular uses the semicolon else syntax pointing to a template reference variable on an <ng-template>.)
Q4. In modern Angular 17, what is the new built-in template syntax replacing *ngIf?
✅ Correct Answer: Option A
Explanation: (Angular 17 introduced built-in control flow with '@if' and '@else', offering cleaner syntax without importing CommonModule.)
Topic 15 Interview Questions & Answers
Q1: What is the desugared syntax of *ngIf under the hood? ▼
Answer: The asterisk is syntactic sugar. Angular transforms <div *ngIf='condition'>Hello</div> into an <ng-template [ngIf]='condition'><div>Hello</div></ng-template> using ViewContainerRef and TemplateRef.
Q2: Can you store the result of an *ngIf condition into a local variable? ▼
Answer: Yes, using the 'as' syntax: *ngIf='user$ | async as user'. This unwraps the Observable once and creates a local template variable 'user' accessible inside the block.
Q3: When would you prefer [hidden] over *ngIf? ▼
Answer: When a component or element has an expensive creation cost (like a complex map, rich text editor, or chart) and is toggled frequently. [hidden] keeps it in the DOM, avoiding re-initialization.
Q4: What happens to child component lifecycle hooks when an *ngIf turns false? ▼
Answer: When *ngIf becomes false, child components inside that block are destroyed, and their ngOnDestroy() lifecycle hook is executed.

16. *ngFor, ngSwitch, ngClass & ngStyle

Beginner
Master Angular's primary structural and attribute directives to repeat lists with *ngFor, handle multiple branches with ngSwitch, and dynamically apply CSS styles.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of *ngFor like a photocopier churning out student admission tickets for an entire auditorium!
  • *ngFor Directive: Loops through an array to render list items: <li *ngFor='let item of items; let i = index'>.
  • trackBy in *ngFor: Greatly optimizes performance by tracking items by unique ID, avoiding full DOM re-renders on list changes.
  • [ngClass]: Dynamically applies CSS classes using an object map: [ngClass]='{ active: isOnline, danger: hasErrors }'.
  • [ngStyle]: Applies dynamic inline CSS styles: [ngStyle]='{ color: textColor, fontSize: size + "px" }'.
💻 16. Rendering Lists with *ngFor & Dynamic Styling
Output Terminal Standard Output
Click "▶ Run" to execute program output.
🧠 Topic 16 Practice Quiz (4 Questions)
Q1. What is the correct syntax for an *ngFor loop in Angular?
✅ Correct Answer: Option A
Explanation: (Angular uses the JavaScript 'for...of' syntax: *ngFor='let item of items'.)
Q2. What is the purpose of the 'trackBy' function in an *ngFor directive?
✅ Correct Answer: Option C
Explanation: (trackBy tells Angular how to identify unique items so it only modifies DOM nodes that actually changed.)
Q3. Which directive conditionally adds or removes CSS classes using an object map?
✅ Correct Answer: Option B
Explanation: ([ngClass] takes an object where keys are class names and values are booleans determining whether the class is added.)
Q4. In modern Angular 17, what is the new built-in block replacing *ngFor?
✅ Correct Answer: Option D
Explanation: (Angular 17 introduced built-in '@for' loops with mandatory 'track' expressions for maximum performance.)
Topic 16 Interview Questions & Answers
Q1: What exported contextual variables does *ngFor provide? ▼
Answer: 1. index: number (current item index). 2. first: boolean (true if first item). 3. last: boolean (true if last item). 4. even: boolean (true if even index). 5. odd: boolean (true if odd index).
Q2: Why is trackBy mandatory in Angular 17's new @for block? ▼
Answer: Without tracking, modifying any item in an array forces Angular to tear down and recreate all DOM elements in the list. Making track mandatory guarantees optimal rendering performance by default.
Q3: How does ngSwitch work? ▼
Answer: ngSwitch is an attribute directive bound to a container, with structural child directives: [ngSwitch]='val' containing <div *ngSwitchCase='"A"'> and <div *ngSwitchDefault>.
Q4: What is the difference between [style.color]='color' and [ngStyle]? ▼
Answer: [style.color] sets a single CSS style property directly. [ngStyle] accepts an object map ({ 'color': 'red', 'font-size': '16px' }) to apply multiple inline styles at once.

17. Uppercase & Lowercase Pipes

Beginner
Pipes transform displayed data in templates without altering the original property in TypeScript. Learn how to transform strings using uppercase, lowercase, and titlecase pipes.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of Pipes like a water purification filter: raw water enters one end and clean sparkling water exits the tap!
  • The Pipe Character (|): Place the pipe symbol (|) after an expression followed by the pipe name: {{ name | uppercase }}.
  • Pure Data Transformation: Pipes do not change the underlying variable; they only change how it appears to the user.
  • Built-in Text Pipes: uppercase (HELLO), lowercase (hello), and titlecase (Hello World).
  • Chaining Pipes: You can chain multiple pipes together: {{ message | slice:0:10 | uppercase }}.
💻 17. Transforming Text with Built-in Pipes
Output Terminal Standard Output
Click "▶ Run" to execute program output.
🧠 Topic 17 Practice Quiz (4 Questions)
Q1. What symbol is used to apply a pipe in an Angular template?
✅ Correct Answer: Option C
Explanation: (The vertical pipe character (|) applies a transformation pipe to an expression.)
Q2. Does applying the uppercase pipe ({{ name | uppercase }}) modify the original 'name' variable in TypeScript?
✅ Correct Answer: Option D
Explanation: (Pipes only affect the displayed output on screen; the underlying component property remains unchanged.)
Q3. Which pipe capitalizes the first letter of every word in a sentence?
✅ Correct Answer: Option B
Explanation: (The 'titlecase' pipe transforms text to title case, capitalizing the first letter of each word.)
Q4. Can you chain multiple pipes together in a single template expression?
✅ Correct Answer: Option A
Explanation: (Pipes can be chained in sequence, passing the output of one pipe as the input to the next.)
Topic 17 Interview Questions & Answers
Q1: What is a Pure Pipe vs an Impure Pipe in Angular? ▼
Answer: A Pure Pipe (default, pure: true) only executes when it detects a pure change to the input value (primitive change or new object reference). An Impure Pipe (pure: false) executes on every change detection cycle, regardless of input changes.
Q2: Why are pipes better than calling methods inside template interpolation? ▼
Answer: Pipes are memoized and only recompute when their inputs change by reference. Method calls inside templates execute on every single change detection cycle, degrading rendering performance.
Q3: How do you pass parameters to a pipe? ▼
Answer: Using a colon (:): {{ value | slice:0:5 }} or multiple parameters with multiple colons: {{ date | date:'fullDate':'UTC' }}.
Q4: Which module must be imported in a standalone component to use built-in pipes? ▼
Answer: CommonModule (from @angular/common) or you can import individual pipes directly (e.g. imports: [UpperCasePipe, DatePipe]) in modern Angular.

18. Date, Currency, Percent & Custom Pipes

Intermediate
Format numbers, currencies, dates, and build your own custom reusable pipes to format data exactly how your users expect.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of Currency Pipes like a foreign currency exchange booth at an international airport converting raw numbers into ₹, $, or € symbols!
  • DatePipe: Formats timestamps: {{ today | date:'mediumDate' }} or {{ today | date:'dd/MM/yyyy' }}.
  • CurrencyPipe: Formats money with currency symbols: {{ price | currency:'INR':'symbol' }}.
  • PercentPipe: Formats decimals as percentages: {{ 0.85 | percent:'1.1-2' }} -> 85.0%.
  • Creating a Custom Pipe: Decorate a class with @Pipe({ name: 'myPipe', standalone: true }) and implement PipeTransform interface with transform() method.
💻 18. Formatting Financials & Custom Truncate Pipe
Output Terminal Standard Output
Click "▶ Run" to execute program output.
🧠 Topic 18 Practice Quiz (4 Questions)
Q1. Which interface must a custom Angular pipe implement?
✅ Correct Answer: Option B
Explanation: (A custom pipe must implement the PipeTransform interface and its transform() method.)
Q2. How do you pass the currency code 'INR' and symbol to the currency pipe?
✅ Correct Answer: Option A
Explanation: (The currency pipe accepts ISO currency codes like 'USD', 'EUR', or 'INR' as arguments.)
Q3. What decorator is used to register a custom pipe class?
✅ Correct Answer: Option C
Explanation: (The @Pipe decorator marks the class as a pipe and defines its template invocation name.)
Q4. What is the output of {{ 0.75 | percent }}?
✅ Correct Answer: Option D
Explanation: (The percent pipe multiplies decimals by 100 and formats them with a percentage sign.)
Topic 18 Interview Questions & Answers
Q1: How do you create a custom pipe using the Angular CLI? ▼
Answer: Run 'ng generate pipe pipes/truncate' (or 'ng g p pipes/truncate'). The CLI generates the pipe class and test spec automatically.
Q2: What parameters does the transform() method in PipeTransform take? ▼
Answer: The first parameter is always the input value to transform. Subsequent parameters are optional configuration arguments passed via colons in the template (e.g. transform(value: string, limit: number, trail: string)).
Q3: When would you intentionally create an Impure Pipe? ▼
Answer: When the pipe needs to detect changes inside arrays or objects (internal property mutations) without the object reference changing, or when reading from dynamic external states (like translations or streams).
Q4: What is the AsyncPipe and why is it considered one of Angular's best features? ▼
Answer: The AsyncPipe automatically subscribes to an Observable or Promise in the template, emits the latest values, triggers change detection, and automatically unsubscribes when the component unmounts to prevent memory leaks.

19. Creating Injectable Services

Intermediate
Services are singleton classes where you organize reusable business logic, state, and HTTP communication, separating them from UI components.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of an Injectable Service like a catering company supplying food to weddings, birthdays, and corporate events from one central kitchen!
  • Why Services? Components should only care about displaying UI. Data fetching and business logic belong inside reusable Services.
  • The @Injectable Decorator: Marks a TypeScript class as a service that can be injected into components.
  • providedIn: 'root': Registers the service as an application-wide singleton instance. Only one instance exists for the entire app.
  • Creating via CLI: Run 'ng g s services/course' to generate a service.
💻 19. Building a Course Data Service
Output Terminal Standard Output
Click "▶ Run" to execute program output.
🧠 Topic 19 Practice Quiz (4 Questions)
Q1. Which decorator marks a class as an Angular service?
✅ Correct Answer: Option D
Explanation: (@Injectable() tells Angular that the class can be managed and provided by the dependency injection system.)
Q2. What does 'providedIn: "root"' do inside @Injectable()?
✅ Correct Answer: Option C
Explanation: ('providedIn: "root"' provides the service at the root injector level as an application-wide singleton.)
Q3. Which Angular CLI command creates a new service named 'auth'?
✅ Correct Answer: Option A
Explanation: ('ng g s auth' (or 'ng generate service auth') creates the service and its unit test.)
Q4. Why should data fetching logic be placed in services rather than components?
✅ Correct Answer: Option B
Explanation: (Separating data logic into services makes components lightweight and keeps code clean and testable.)
Topic 19 Interview Questions & Answers
Q1: What is the Singleton design pattern in Angular services? ▼
Answer: A Singleton ensures that only one single instance of a service class is created in memory. Every component that injects the service shares this exact same instance and its state.
Q2: What happens if a service is provided in a component's 'providers: [...]' array instead of 'root'? ▼
Answer: Angular creates a new, separate instance of the service for that component and its children. The instance is destroyed when the component is unmounted.
Q3: What is Tree-Shaking of services in Angular? ▼
Answer: With 'providedIn: "root"', if a service is never injected anywhere in your code, the bundler automatically removes it (tree-shakes it) from the final production bundle to reduce download size.
Q4: Can a service inject another service in Angular? ▼
Answer: Yes. Services can inject other services (e.g. AuthService can inject HttpClient) using constructor injection or the inject() function.

20. Using Service & Dependency Injection

Intermediate
Learn how components consume services using Angular's Dependency Injection (DI) system through constructor injection or the modern inject() function.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of Dependency Injection like ordering room service in a 5-star hotel: you don't cook the food yourself; the hotel delivers it right to your suite!
  • Constructor Injection: constructor(private courseService: CourseService) {} - Angular injects the singleton automatically.
  • The modern inject() function: In modern Angular: private courseService = inject(CourseService); (no constructor needed!).
  • Sharing State: When Component A modifies data in the service, Component B reads the updated data immediately.
  • Loose Coupling: Components don't use 'new CourseService()'. Angular manages the creation and lifecycle.
💻 20. Injecting Service into a Component
Output Terminal Standard Output
Click "▶ Run" to execute program output.
🧠 Topic 20 Practice Quiz (4 Questions)
Q1. How does Angular provide services to components without using the 'new' keyword?
✅ Correct Answer: Option A
Explanation: (Angular's Dependency Injection system resolves and supplies service instances automatically.)
Q2. What is the modern Angular function to inject a dependency without a constructor?
✅ Correct Answer: Option B
Explanation: (The 'inject()' function (Angular 14+) allows clean dependency injection directly at the property declaration level.)
Q3. What happens if you manually write 'const s = new CourseService()' inside a component?
✅ Correct Answer: Option D
Explanation: (Manual instantiation with 'new' bypasses DI, meaning the component won't share the singleton instance with other components.)
Q4. What is the hierarchical injector tree in Angular?
✅ Correct Answer: Option C
Explanation: (Angular's DI is hierarchical: a service can be scoped to root, to a route branch, or to an individual component.)
Topic 20 Interview Questions & Answers
Q1: What are the advantages of Angular's Dependency Injection system? ▼
Answer: DI enables loose coupling, simplifies unit testing (you can easily mock services), centralizes instance management, promotes reusability, and eliminates hardcoded dependencies.
Q2: How do you mock a service when writing unit tests for an Angular component? ▼
Answer: In TestBed.configureTestingModule, provide a mock object using: { provide: CourseService, useValue: mockCourseService } or useClass: MockCourseService.
Q3: What is the difference between constructor injection and the inject() function? ▼
Answer: Constructor injection is the traditional way. The inject() function can be used in field initializers, factory functions, route guards, and functional interceptors where constructor access isn't available.
Q4: What error occurs if Angular cannot find a provider for an injected token? ▼
Answer: NullInjectorError: No provider for ServiceName! This occurs when a service is neither marked providedIn: 'root' nor listed in the component's providers array.

21. Defining App Routes & AppRoutingModule

Intermediate
Routing enables Single Page Application navigation. Define routes that map URL paths to specific components without reloading the browser.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of Routing like highway road signs pointing to different destinations without changing the car!
  • Routes Array: const routes: Routes = [{ path: '', component: HomeComponent }, { path: 'courses', component: CoursesComponent }];
  • Wildcard Route (**): { path: '**', component: NotFoundComponent } catches all unmatched URLs to show a 404 page.
  • Redirects: { path: '', redirectTo: '/home', pathMatch: 'full' } redirects empty paths to default pages.
  • provideRouter(): In modern standalone apps, routes are registered in app.config.ts via provideRouter(routes).
💻 21. Defining Route Configuration
Output Terminal Standard Output
Click "▶ Run" to execute program output.
🧠 Topic 21 Practice Quiz (4 Questions)
Q1. What type represents a list of route definitions in Angular Router?
✅ Correct Answer: Option C
Explanation: ('Routes' is the official type array from @angular/router representing route definitions.)
Q2. Which route path acts as a wildcard to catch all unmatched URLs for a 404 page?
✅ Correct Answer: Option B
Explanation: (The double asterisk '**' matches every URL that did not match any previous route in the array.)
Q3. Why must the wildcard route ('**') always be placed at the very END of the routes array?
✅ Correct Answer: Option A
Explanation: (Angular uses a first-match-wins strategy. If '**' is placed first, it would catch every request, preventing other routes from matching.)
Q4. What does 'pathMatch: "full"' mean on a redirect route?
✅ Correct Answer: Option D
Explanation: ('pathMatch: "full"' ensures that the redirect only triggers if the URL is completely empty, rather than just starting with an empty string.)
Topic 21 Interview Questions & Answers
Q1: How does 'loadComponent' enable Lazy Loading in Angular routes? ▼
Answer: loadComponent uses native dynamic ES imports (import('./path')). Angular splits that component into a separate JavaScript bundle chunk that is only downloaded over the network when the user actually navigates to that route.
Q2: How do you read dynamic route parameters like '/courses/:id'? ▼
Answer: Inject the ActivatedRoute service: private route = inject(ActivatedRoute); then read it synchronously via this.route.snapshot.paramMap.get('id') or reactively via this.route.paramMap.
Q3: What is the difference between PathLocationStrategy and HashLocationStrategy? ▼
Answer: PathLocationStrategy uses HTML5 pushState (clean URLs like /courses), which requires server rewrite configuration. HashLocationStrategy uses URL hashes (#/courses), which works on any server without rewrite rules.
Q4: How do you pass query parameters (e.g. /search?q=angular)? ▼
Answer: Use [queryParams]='{ q: "angular" }' on routerLink or navigate(['/search'], { queryParams: { q: 'angular' } }). Read them using route.queryParams.

22. RouterLink & RouterOutlet

Intermediate
Connect your navigation links to routes using the RouterLink directive, and display active route views inside the <router-outlet> placeholder.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of router-outlet like a movie theater projection screen: the theater room stays identical, but the movie projected on the screen changes!
  • <router-outlet>: Acts as a placeholder in your template where Angular dynamically inserts the active routed component.
  • routerLink directive: Use [routerLink]="['/courses']" on <a> tags to navigate client-side without full page reloads.
  • routerLinkActive: Automatically applies an active CSS class when the route matches: routerLinkActive='active-tab'.
  • Programmatic Navigation: Inject the Router service to navigate in code: this.router.navigate(['/dashboard']);
💻 22. App Layout with RouterLink & Outlet
Output Terminal Standard Output
Click "▶ Run" to execute program output.
🧠 Topic 22 Practice Quiz (4 Questions)
Q1. What is the purpose of the <router-outlet></router-outlet> tag in Angular?
✅ Correct Answer: Option B
Explanation: (<router-outlet> is the view placeholder where Angular inserts components matched by the active route.)
Q2. Which directive replaces the standard HTML 'href' on anchor tags to prevent page reloads?
✅ Correct Answer: Option C
Explanation: (routerLink intercepts clicks and performs client-side routing without triggering a full page reload.)
Q3. Which directive adds a CSS class to a link when its corresponding route is active?
✅ Correct Answer: Option D
Explanation: (routerLinkActive toggles a specified CSS class on navigation elements when the linked route is active.)
Q4. How do you navigate programmatically inside a TypeScript class method?
✅ Correct Answer: Option A
Explanation: (Injecting the Router service and calling 'router.navigate()' handles programmatic client-side redirection.)
Topic 22 Interview Questions & Answers
Q1: What is the difference between [routerLink]="['/path']" and routerLink="/path"? ▼
Answer: String literal syntax 'routerLink="/path"' is for static paths. Array binding '[routerLink]="['/path', id]"' allows passing dynamic parameters or segments into the route array.
Q2: Can you have multiple <router-outlet> tags on a single page? ▼
Answer: Yes. In addition to the primary outlet, you can define auxiliary (named) outlets: <router-outlet name='sidebar'></router-outlet> to display secondary views (like popups or chat sidebars) independently.
Q3: What option does routerLinkActiveOptions provide? ▼
Answer: By default, routerLinkActive matches partially (e.g. /home matches /home/details). Setting [routerLinkActiveOptions]='{ exact: true }' ensures the active class only applies when the URL matches exactly.
Q4: What lifecycle events does the Router service emit during navigation? ▼
Answer: NavigationStart, RoutesRecognized, GuardsCheckStart, GuardsCheckEnd, ResolveStart, ResolveEnd, NavigationEnd, NavigationCancel, and NavigationError.

23. Template-Driven & Reactive Forms

Intermediate
Angular provides two distinct paradigms for handling forms: Template-Driven Forms (easy, template-focused) and Reactive Forms (robust, scalable, model-driven).
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of Reactive Forms like an automated airport passport e-gate checking every biometric detail before letting the traveler through!
  • Template-Driven Forms: Driven by directives in HTML (ngModel, ngForm). Ideal for simple forms with straightforward validation.
  • Reactive Forms: Defined programmatically in TypeScript using FormControl, FormGroup, and FormBuilder. High scalability and testability.
  • ReactiveFormsModule: Must be imported in your standalone component imports to use Reactive Forms.
  • FormGroup & FormControl: A FormControl manages a single input field; a FormGroup manages a collection of FormControls (like an entire form).
💻 23. Building a Reactive Form with FormBuilder
Output Terminal Standard Output
Click "▶ Run" to execute program output.
🧠 Topic 23 Practice Quiz (4 Questions)
Q1. Which module must be imported to use Reactive Forms in Angular?
✅ Correct Answer: Option D
Explanation: (ReactiveFormsModule provides FormGroup, FormControl, FormBuilder, and reactive directives.)
Q2. What is the primary difference between Template-Driven and Reactive Forms?
✅ Correct Answer: Option A
Explanation: (Reactive forms define controls, validations, and state in TypeScript, making them predictable, scalable, and easy to unit test.)
Q3. What is a FormControl in Angular?
✅ Correct Answer: Option B
Explanation: (FormControl is the fundamental building block that tracks the value and validation status of a single input.)
Q4. What helper service provides a convenient syntax to generate FormGroups and FormControls?
✅ Correct Answer: Option C
Explanation: (FormBuilder provides shorthand syntax (fb.group({ ... })) to construct form models with minimal boilerplate.)
Topic 23 Interview Questions & Answers
Q1: Why do enterprise applications almost universally prefer Reactive Forms over Template-Driven Forms? ▼
Answer: Reactive Forms offer synchronous data access, immutable data flows, strong TypeScript typing, dynamic runtime field addition (FormArray), seamless testing without DOM dependencies, and easy integration with RxJS streams (valueChanges).
Q2: What is a FormArray in Reactive Forms? ▼
Answer: A FormArray manages an array of FormControls, FormGroups, or nested FormArrays. It is designed for dynamically growing forms where users can add or remove fields (like adding multiple phone numbers or line items).
Q3: How can you listen to real-time changes on a FormControl? ▼
Answer: Every FormControl exposes a 'valueChanges' Observable: this.studentForm.get('email')?.valueChanges.subscribe(val => console.log(val)); You can pipe it with debounceTime() to build real-time search inputs.
Q4: What is the difference between setValue() and patchValue() on a FormGroup? ▼
Answer: setValue() strictly requires values for EVERY control in the group and throws an error if any property is missing. patchValue() updates only the specified properties, ignoring missing ones.

24. Form Validation Rules (Required & Email)

Intermediate
Ensure user input is accurate and clean using built-in Angular validators (required, email, minLength, pattern) and display friendly inline error messages.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of Form Validation like an inspector stamping passports: highlighting missing signatures in red!
  • Built-in Validators: Validators.required, Validators.email, Validators.minLength(n), Validators.maxLength(n), Validators.pattern(/regex/).
  • Control States: valid (passes all rules), invalid (fails rules), touched (user focused & left input), dirty (user typed in input).
  • Displaying Conditional Errors: Show error messages only when the user has touched the input: *ngIf='control.invalid && control.touched'.
  • Custom Validators: Write custom validator functions that return ValidationErrors | null (e.g. password match validator).
💻 24. Validating Forms with Error Messages
Output Terminal Standard Output
Click "▶ Run" to execute program output.
🧠 Topic 24 Practice Quiz (4 Questions)
Q1. What does the 'touched' property on a FormControl mean?
✅ Correct Answer: Option A
Explanation: ('touched' becomes true once the input has lost focus (blur event).)
Q2. What does the 'dirty' property on a FormControl indicate?
✅ Correct Answer: Option D
Explanation: ('dirty' means the user has changed the value of the control. 'pristine' means it hasn't been changed.)
Q3. Which built-in validator verifies that an input is not empty?
✅ Correct Answer: Option C
Explanation: (Validators.required enforces that the control value is neither empty nor null.)
Q4. What must a custom validator function return if the value is VALID?
✅ Correct Answer: Option B
Explanation: (Angular validators return 'null' when the value is valid, and an error object (e.g. { invalidAge: true }) when invalid.)
Topic 24 Interview Questions & Answers
Q1: What is an Asynchronous Validator in Angular? ▼
Answer: An async validator performs asynchronous validation tasks (like an HTTP request to check if a username or email is already taken in the database). It returns a Promise or Observable of ValidationErrors | null.
Q2: How do you create a Cross-Field Validator (e.g. confirming password match)? ▼
Answer: Apply the validator to the parent FormGroup instead of a single control: fb.group({ password: '', confirm: '' }, { validators: passwordMatchValidator }). Inside the validator, compare form.get('password').value with form.get('confirm').value.
Q3: What are the four states of form control validity? ▼
Answer: VALID (passes all rules), INVALID (fails at least one rule), PENDING (async validation is currently in progress), and DISABLED (exempt from validation checks).
Q4: How can you trigger all validation error messages on submit if the user hasn't touched the fields? ▼
Answer: Call this.userForm.markAllAsTouched(). This marks all child controls as touched, causing all validation error messages to display immediately.

25. HttpClientModule & GET API Requests

Advanced
Communicate with REST APIs using Angular's HttpClient service. Learn how to perform HTTP GET requests, parse JSON data automatically, and handle typed responses with RxJS Observables.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of HttpClient like a diplomatic courier carrying encrypted diplomatic mail to and from distant cloud servers!
  • HttpClient Service: Angular's built-in HTTP service providing get(), post(), put(), and delete() methods returning RxJS Observables.
  • provideHttpClient(): In modern Angular, register the HTTP client in app.config.ts: provideHttpClient().
  • Typed Responses: Specify the expected response interface: this.http.get<User[]>('https://api.example.com/users').
  • Observables & subscribe(): HTTP requests in Angular are cold Observables; they only execute when you call .subscribe() or use the | async pipe in templates.
💻 25. Fetching Data with HttpClient.get()
Output Terminal Standard Output
Click "▶ Run" to execute program output.
🧠 Topic 25 Practice Quiz (4 Questions)
Q1. What type do HttpClient methods (like http.get()) return in Angular?
✅ Correct Answer: Option C
Explanation: (Angular's HttpClient returns RxJS Observables, providing operators like map, catchError, and retry.)
Q2. How do you enable HttpClient in a modern standalone Angular application?
✅ Correct Answer: Option A
Explanation: ('provideHttpClient()' is the official way to register the HTTP client in standalone apps.)
Q3. What happens if you call http.get(url) but NEVER call .subscribe() and don't use the async pipe?
✅ Correct Answer: Option D
Explanation: (Observables are cold. Unless something subscribes to them, no network request will ever be initiated.)
Q4. Does Angular's HttpClient require manual 'response.json()' parsing like the browser fetch() API?
✅ Correct Answer: Option B
Explanation: (HttpClient automatically parses the JSON body, saving you from writing manual response.json() code.)
Topic 25 Interview Questions & Answers
Q1: What is an HTTP Interceptor in Angular? ▼
Answer: An HTTP Interceptor inspects and transforms outgoing HTTP requests and incoming responses globally. Common use cases include attaching JWT bearer authentication tokens to headers, logging request timings, and centralized error handling.
Q2: How does the AsyncPipe solve memory leaks with HTTP Observables? ▼
Answer: When you bind an Observable in a template with | async (e.g. *ngFor='let u of users$ | async'), the AsyncPipe automatically subscribes and unsubscribes when the component is destroyed, preventing memory leaks.
Q3: How do you handle HTTP errors in Angular services using RxJS? ▼
Answer: By piping the catchError operator: return this.http.get(url).pipe(catchError(this.handleError)). In the error handler, log the error and return throwError(() => new Error('Custom message')).
Q4: What is the difference between an Observable and a Promise? ▼
Answer: A Promise is eager, emits a single value, and cannot be cancelled. An Observable is lazy (cold), can emit multiple values over time (streams), can be cancelled (unsubscribed), and supports rich transform operators (map, filter, debounce, retry).

26. POST API Requests & RxJS Basics

Advanced
Send data to backend servers with HTTP POST requests, and unlock the power of RxJS reactive operators like map, filter, debounceTime, and catchError.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of RxJS Observables like a continuous conveyor belt of fresh sushi plates where diners grab only the rolls they subscribe to!
  • HTTP POST Requests: this.http.post<ResponseModel>(url, payload) sends new records to server endpoints.
  • What is RxJS? Reactive Extensions for JavaScript - a library for composing asynchronous and event-based programs using observable sequences.
  • Common RxJS Operators: map() (transforms data), filter() (filters emissions), catchError() (catches errors), and debounceTime() (delays high-frequency events).
  • Async Pipe Advantage: The template pipe {{ data$ | async }} automatically subscribes and unsubscribes for you.
💻 26. Sending POST Request & RxJS Pipe Transformation
Output Terminal Standard Output
Click "▶ Run" to execute program output.
🧠 Topic 26 Practice Quiz (4 Questions)
Q1. What is the primary role of the HTTP POST method?
✅ Correct Answer: Option B
Explanation: (HTTP POST sends a payload body to a server endpoint to create new data records.)
Q2. Which RxJS operator transforms items emitted by an Observable into another format?
✅ Correct Answer: Option D
Explanation: (The 'map()' operator applies a transformation function to each value emitted by the source Observable.)
Q3. Which RxJS operator catches errors in an Observable sequence and handles them gracefully?
✅ Correct Answer: Option A
Explanation: (catchError() intercepts errors on the stream, allowing you to return a fallback Observable.)
Q4. What does the 'debounceTime(300)' operator do in a search input stream?
✅ Correct Answer: Option C
Explanation: (debounceTime prevents spamming the backend by waiting for the user to stop typing before emitting.)
Topic 26 Interview Questions & Answers
Q1: What is the difference between switchMap, mergeMap, and concatMap in RxJS? ▼
Answer: switchMap cancels previous in-flight requests and switches to the new one (ideal for search-as-you-type). mergeMap handles multiple requests concurrently. concatMap executes requests strictly in sequential order.
Q2: What is a Subject and a BehaviorSubject in RxJS? ▼
Answer: A Subject is both an Observable and an Observer (multicast to many subscribers). A BehaviorSubject requires an initial value and immediately emits its current/latest value to any new subscriber upon subscription.
Q3: Why is it important to unsubscribe from RxJS subscriptions in ngOnDestroy? ▼
Answer: Long-lived subscriptions to global services or events keep components alive in memory even after they are removed from the DOM, causing memory leaks. Unsubscribe using Subject with takeUntilDestroyed() or takeUntil().
Q4: What is takeUntilDestroyed() introduced in modern Angular? ▼
Answer: takeUntilDestroyed() is an operator that automatically ties the lifetime of an Observable subscription to the component's DestroyRef, completing the subscription automatically when the component is destroyed.

27. Component Lifecycle Hooks

Advanced
Every Angular component has a lifecycle managed by Angular. Tap into key lifecycle events like creation, input change detection, and unmounting with lifecycle hooks.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of Lifecycle Hooks like stages of a space rocket launch: countdown (ngOnInit), orbit (ngDoCheck), and splashdown (ngOnDestroy)!
  • ngOnInit(): Called once after Angular initializes the component's input properties. The standard place for initial data loading.
  • ngOnChanges(): Called whenever one or more @Input() properties change from the parent component.
  • ngOnDestroy(): Called immediately before Angular destroys the component. Critical for clearing timers and unsubscribing from observables.
  • ngAfterViewInit(): Called after Angular initializes the component's view and child views (@ViewChild).
💻 27. Managing Component Lifecycle & Cleanup
Output Terminal Standard Output
Click "▶ Run" to execute program output.
🧠 Topic 27 Practice Quiz (4 Questions)
Q1. Which lifecycle hook is called right after Angular sets input properties and is the best place to fetch initial data?
✅ Correct Answer: Option D
Explanation: (ngOnInit() is called once after inputs are bound, making it the standard hook for data fetching.)
Q2. Which lifecycle hook is called when an @Input() property changes value from the parent?
✅ Correct Answer: Option B
Explanation: (ngOnChanges() executes before ngOnInit and whenever one or more @Input() data-bound properties change.)
Q3. What should you always do inside ngOnDestroy()?
✅ Correct Answer: Option C
Explanation: (ngOnDestroy() is the cleanup hook where you release resources and cancel intervals to prevent memory leaks.)
Q4. What is the new modern alternative to ngOnDestroy() in Angular 16+?
✅ Correct Answer: Option A
Explanation: (Angular 16 introduced DestroyRef, allowing you to register cleanup callbacks anywhere using inject(DestroyRef).)
Topic 27 Interview Questions & Answers
Q1: List the chronological order of Angular lifecycle hooks. ▼
Answer: 1. ngOnChanges 2. ngOnInit 3. ngDoCheck 4. ngAfterContentInit 5. ngAfterContentChecked 6. ngAfterViewInit 7. ngAfterViewChecked 8. ngOnDestroy.
Q2: What information does SimpleChanges provide in ngOnChanges? ▼
Answer: For each changed input property, SimpleChanges provides previousValue, currentValue, and isFirstChange() boolean.
Q3: Why shouldn't you access a @ViewChild element inside ngOnInit? ▼
Answer: Because the component's view and DOM child elements have not finished rendering when ngOnInit runs. You must wait for ngAfterViewInit() before accessing @ViewChild DOM nodes.
Q4: What is ngDoCheck and when should it be used? ▼
Answer: ngDoCheck runs on every change detection cycle. It is used to detect and act upon custom changes that Angular's default algorithm cannot automatically detect (such as mutations deep inside objects without changing references).

28. Parent-Child Communication (@Input & @Output)

Advanced
Pass data down from parent to child using @Input(), and emit custom events up from child to parent using @Output() and EventEmitter.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of @Input and @Output like a walkie-talkie conversation between a spaceship commander and ground control!
  • @Input() Decorator: Allows a parent to pass data into a child component: @Input() productTitle: string = '';
  • @Output() & EventEmitter: Allows a child to send events up to its parent: @Output() deleteEvent = new EventEmitter<number>();
  • Parent Listens: The parent binds to the custom event using standard event syntax: <app-child (deleteEvent)='onDelete($event)'>.
  • Signals input() & output(): In modern Angular 17+, you can also use new signal-based input() and output() functions.
💻 28. Parent-Child Data Exchange
Output Terminal Standard Output
Click "▶ Run" to execute program output.
🧠 Topic 28 Practice Quiz (4 Questions)
Q1. Which decorator allows a parent component to pass data into a child component?
✅ Correct Answer: Option A
Explanation: (@Input() marks a property as receivable from a parent component via property binding.)
Q2. What class is used with @Output() to emit custom events to parent components?
✅ Correct Answer: Option C
Explanation: (EventEmitter is used with @Output() to emit custom events containing a payload.)
Q3. How does the parent access the data payload emitted by a child's @Output() event?
✅ Correct Answer: Option B
Explanation: ($event contains the value passed into .emit(value) by the child component.)
Q4. How can you make an @Input property mandatory in Angular 16+?
✅ Correct Answer: Option D
Explanation: (Angular 16 introduced required inputs via '@Input({ required: true })', causing compile errors if the parent omits it.)
Topic 28 Interview Questions & Answers
Q1: How do you achieve communication between two sibling components with no direct parent-child relationship? ▼
Answer: By using a shared Injectable Service with a Subject or BehaviorSubject (or an Angular Signal). One sibling pushes data into the service, and the other sibling subscribes to receive updates.
Q2: What is @ViewChild and how does it differ from @Input? ▼
Answer: @Input passes data declaratively from parent to child template. @ViewChild gives the parent direct programmatic access to the child component class instance, allowing it to call child methods directly.
Q3: What are the new Signal-based inputs introduced in Angular 17.1? ▼
Answer: The input() function (e.g. title = input<string>('default');) returns a Signal instead of using the @Input() decorator. It integrates directly with Angular's reactive Signal system.
Q4: What is an input transform function in Angular 16+? ▼
Answer: A transform function converts incoming input values before assigning them (e.g. @Input({ transform: booleanAttribute }) disabled: boolean). This allows <app-btn disabled> without writing [disabled]='true'.

29. Route Guards & Auth Protection

Advanced
Route Guards protect sensitive routes (like user dashboards and admin panels) from unauthorized access, redirecting unauthenticated users to the login screen.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of Route Guards like a VIP security guard at a private club door checking membership cards before granting access!
  • CanActivate Guard: Determines whether a user is allowed to navigate to a route (e.g. checking authentication tokens).
  • CanDeactivate Guard: Prevents users from accidentally navigating away if they have unsaved changes in a form.
  • Functional Guards: Modern Angular uses clean functional guards like 'canActivate: [authGuard]' instead of boilerplate classes.
  • Returning UrlTree: If unauthorized, guards return a router.createUrlTree(['/login']) to automatically redirect the user.
💻 29. Modern Functional Auth Guard
Output Terminal Standard Output
Click "▶ Run" to execute program output.
🧠 Topic 29 Practice Quiz (4 Questions)
Q1. Which route guard determines whether a user can navigate to a specific route?
✅ Correct Answer: Option C
Explanation: (CanActivate checks permissions before allowing navigation to a route.)
Q2. Which route guard checks if a user has unsaved changes before leaving a page?
✅ Correct Answer: Option D
Explanation: (CanDeactivate executes before leaving a route, ideal for prompting 'You have unsaved changes'.)
Q3. What should a modern functional guard return to redirect unauthorized users to the login page?
✅ Correct Answer: Option B
Explanation: (Returning a UrlTree (router.createUrlTree(['/login'])) cancels current navigation and cleanly redirects to the login route.)
Q4. In which file are route guards attached to routes?
✅ Correct Answer: Option A
Explanation: (Guards are attached in the route configuration object: { path: 'admin', component: AdminComponent, canActivate: [authGuard] }.)
Topic 29 Interview Questions & Answers
Q1: What is the difference between class-based guards and modern functional guards in Angular? ▼
Answer: Class-based guards implemented interfaces like CanActivate and required declaring full Injectable classes. Modern Angular (v15+) uses functional guards (CanActivateFn), which are simple functions using the inject() function, eliminating boilerplate.
Q2: What return types can a CanActivate guard return? ▼
Answer: A boolean, a UrlTree, or an Observable/Promise that resolves to a boolean or UrlTree.
Q3: What is the CanMatch guard introduced in Angular 14? ▼
Answer: CanMatch controls whether a route can even be matched. Unlike CanActivate, if CanMatch returns false, Angular continues searching subsequent routes in the array, enabling feature-flagged routes.
Q4: What is a Route Resolver (ResolveFn) in Angular? ▼
Answer: A resolver fetches critical data before navigation finishes. The component does not mount until the resolver resolves, ensuring the page renders with preloaded data.

30. Angular Signals & Modern Reactivity

Advanced
Signals are the future of Angular reactivity (introduced in Angular 16/17+). They track state changes with pinpoint precision, delivering blazing-fast performance without Zone.js.
💡 IN SIMPLE WORDS / REAL-LIFE ANALOGY
Think of Angular Signals like a smart electric power grid: when one solar panel charges up, only connected lights glow brighter with zero wasted energy!
  • What is a Signal? A wrapper around a value that notifies interested consumers when the value changes: const count = signal(0);
  • Reading & Writing: Read by calling it like a function: count(). Update using set(newValue) or update(prev => prev + 1).
  • computed() Signal: A derived signal that automatically re-calculates only when its dependent signals change: const double = computed(() => count() * 2);
  • effect(): Runs a side effect whenever dependent signals change (like logging or saving to localStorage).
💻 30. Building a Reactive Shopping Cart with Signals
Output Terminal Standard Output
Click "▶ Run" to execute program output.
🧠 Topic 30 Practice Quiz (4 Questions)
Q1. How do you read the current value of an Angular Signal in code or templates?
✅ Correct Answer: Option B
Explanation: (Signals are getter functions: you read their current value by calling them: mySignal().)
Q2. Which function creates a derived Signal that automatically re-calculates when dependencies change?
✅ Correct Answer: Option A
Explanation: (computed(() => ...) defines a memoized derived signal that only updates when dependent signals emit changes.)
Q3. How do you update an existing signal value based on its previous value?
✅ Correct Answer: Option C
Explanation: (The .update() method takes a callback function receiving the previous value and returning the new value.)
Q4. What is the major long-term benefit of Signals in Angular?
✅ Correct Answer: Option D
Explanation: (Signals enable granular, direct DOM updates without scanning the entire component tree, paving the way for Zone-less Angular.)
Topic 30 Interview Questions & Answers
Q1: What is an Angular Signal and how does it differ from an RxJS Observable? ▼
Answer: A Signal is synchronous, always has a current value, does not require manual subscription or unsubscription, and is designed for fine-grained UI state. An RxJS Observable is asynchronous, represents streams of events over time, and requires subscription/unsubscription.
Q2: What are the three core primitives of the Angular Signal model? ▼
Answer: 1. signal(initialValue): Writable state. 2. computed(fn): Read-only derived state. 3. effect(fn): Side effect runner that triggers on signal changes.
Q3: What is untracked() in Angular Signals? ▼
Answer: untracked() allows reading a signal inside a computed or effect without creating a reactive dependency on that signal. If the untracked signal changes, the effect will not re-run.
Q4: What is Zone-less Angular? ▼
Answer: Traditionally, Angular relied on Zone.js to monkey-patch asynchronous browser events to trigger global change detection. With Signals, Angular knows the exact components and nodes that changed, enabling Zone-less apps that are faster and have smaller bundle sizes.

📥 Angular - Complete Study Notes

Study Resource
📑

Angular Full Engineering Handbook

🎓 Angular Certificate of Completion

100% Certified
🏆

Official Enterprise Angular Developer Credential

✓ Includes Verification ID • Course Completion Seal • Instant Download