<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dhilip Kumar on Medium]]></title>
        <description><![CDATA[Stories by Dhilip Kumar on Medium]]></description>
        <link>https://medium.com/@dhilip-me?source=rss-bc6e6d0c9eb6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*BraBSe0MP7_jJVM-</url>
            <title>Stories by Dhilip Kumar on Medium</title>
            <link>https://medium.com/@dhilip-me?source=rss-bc6e6d0c9eb6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 23:33:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dhilip-me/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Read later]]></title>
            <link>https://dhilip-me.medium.com/read-later-b1f56473a786?source=rss-bc6e6d0c9eb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1f56473a786</guid>
            <dc:creator><![CDATA[Dhilip Kumar]]></dc:creator>
            <pubDate>Fri, 02 Jan 2026 15:01:29 GMT</pubDate>
            <atom:updated>2026-01-02T15:01:29.400Z</atom:updated>
            <content:encoded><![CDATA[<p>Read later</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1f56473a786" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Pipes]]></title>
            <link>https://dhilip-me.medium.com/angular-pipes-6ccd97de6af1?source=rss-bc6e6d0c9eb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ccd97de6af1</guid>
            <category><![CDATA[pure-pipe]]></category>
            <category><![CDATA[impure-pipe]]></category>
            <category><![CDATA[pipes]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Dhilip Kumar]]></dc:creator>
            <pubDate>Wed, 10 Dec 2025 14:49:37 GMT</pubDate>
            <atom:updated>2025-12-11T08:10:44.840Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What is a pipe in Angular?</strong></p><ul><li>Pipes are used to transform the data. It is used to format or manipulate data before displaying it to user without altering the original data.</li><li>E.g DatePipe, UpperCasePipe etc.</li><li>And PipeTransform interface is used to create a custom pipe.</li></ul><pre>{{ dateObj | date }}               // output is &#39;Jun 15, 2015&#39;<br>{{ dateObj | date:&#39;mm:ss&#39; }}       // output is &#39;43:11&#39;<br><br>&lt;p&gt;{{ myText | uppercase }}&lt;/p&gt;</pre><pre>ng generate pipe trim</pre><pre>import { Pipe, PipeTransform } from &#39;@angular/core&#39;;<br><br>@Pipe({<br>  name: &#39;trim&#39; // This is the name you&#39;ll use in your templates<br>})<br><br>export class TrimPipe implements PipeTransform {<br><br>  transform(value: string): string {<br>    if (!value) {<br>      return &#39;&#39;;<br>    }<br>    return value.trim();<br>  }<br>}</pre><pre>&lt;p&gt;{{ &#39;  Hello World  &#39; | trim }}&lt;/p&gt;</pre><p>Adding Arguments to a Pipe:</p><pre>import { Pipe, PipeTransform } from &#39;@angular/core&#39;;<br><br>@Pipe({<br>  name: &#39;customFormat&#39;<br>})<br><br>export class CustomFormatPipe implements PipeTransform {<br><br>  transform(value: string, prefix: string, suffix: string): string {<br>    if (!value) {<br>      return &#39;&#39;;<br>    }<br><br>    return prefix + &quot;-&quot; + value + &quot;-&quot; + suffix;<br>  }<br>}</pre><pre>&lt;p&gt;{{ &#39;data&#39; | customFormat:&#39;Prefix&#39;:&#39;Suffix&#39; }}&lt;/p&gt;</pre><p>This would output: “Prefix-data-Suffix”.</p><p><strong>What are impure and pure pipes in angular?</strong></p><p>Impure pipes execute during every change detection cycle, whether the input value or parameters have changed. Whereas pure pipes, re-executes only when their input reference changes making it efficient compared to impure pipes.</p><p><strong>Use Cases: </strong>Impure pipes are typically used when:</p><ul><li>The pipe’s output depends on mutable objects. When the pipe needs to react to changes that Angular’s default change detection might not automatically detect (e.g., adding or removing elements from an array).</li></ul><pre>    @Pipe({<br>      name: &#39;myImpurePipe&#39;,<br>      pure: false // Declares this as an impure pipe<br>    })</pre><p><strong>What is an async pipe, and how is it used in Angular templates?</strong></p><ul><li><strong>async pipe</strong> automatically subscribes to an observable or a promise and unwraps the value for you.</li><li>It manages subscriptions and automatically unsubscribes when the component is destroyed avoiding memory leaks.</li></ul><p>Example:</p><p>Suppose you have an observable that fetches data:</p><pre>export class AppComponent {<br>  data$: Observable&lt;Data&gt;;<br>  <br>  constructor(private dataService: DataService) {<br>    this.data$ = this.dataService.getData();<br>  }<br>}</pre><p>In your template, use the async pipe to bind the data:</p><pre>&lt;div *ngIf=&quot;data$ | async as data&quot;&gt;<br>  &lt;p&gt;{{ data.name }}&lt;/p&gt;<br>&lt;/div&gt;</pre><p>Here, the async pipe subscribes to data$, and when the data is available and renders the content.</p><p><strong>Read More:</strong></p><ul><li><a href="https://dhilip-me.medium.com/angular-interview-preparation-db274264c3a1"><strong>Angular_Basics_Overview</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-lifecycle-hooks-mvvm-architecture-a6cca524ac09"><strong>Angular_Lifecycle_Hooks_And_MVVM_Architecture</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-synchronous-and-asynchronous-behaviors-3e1538f067b2"><strong>Angular_Synchronous_and_Asynchronous_Behaviors</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-pipes-6ccd97de6af1"><strong>Angular_Pipes</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/97941c37d897"><strong>Angular_Forms</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-router-586a84463179"><strong>Angular_Routing</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/angular-interceptors-1c918da59884"><strong>Angular_Interceptors</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-web-workers-1a41d79783d3"><strong>Angular_Web_Workers</strong></a></li><li><a href="https://dhilip-me.medium.com/rxjs-in-angular-63ae9902c4b7"><strong>RxJS_in_Angular</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/69d1fbf8a9fc"><strong>Operators_in_RxJS</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-application-optimization-1f59c0074c42"><strong>Angular_Application_Optimization</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/angular-scenario-based-interview-questions-991e8744fcac"><strong>Angular_Scenario_Based_Interview_Question</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ccd97de6af1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Application Optimization]]></title>
            <link>https://dhilip-me.medium.com/angular-application-optimization-1f59c0074c42?source=rss-bc6e6d0c9eb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f59c0074c42</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[memory-leak]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Dhilip Kumar]]></dc:creator>
            <pubDate>Thu, 04 Dec 2025 08:02:28 GMT</pubDate>
            <atom:updated>2025-12-12T09:34:45.630Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>How do you optimize Angular applications?</strong></p><ul><li><strong>Use AOT (Ahead-of-Time) Compilation:</strong> Pre-compile the application to improve startup time and reduce the size of the bundle.</li><li><strong>Lazy Loading: </strong>Load modules only when they are needed to reduce initial loading time.</li><li><strong>OnPush Change Detection:</strong> Use the OnPush change detection strategy to minimize unnecessary checks.</li><li><strong>Tree Shaking:</strong> Remove unused code during the build process to reduce bundle size.</li><li><strong>Minification and Uglification: </strong>Minify and compress JavaScript and CSS files for smaller payloads.</li><li><strong>Use TrackBy with ngFor:</strong> Improves performance by avoiding re-rendering unchanged items.</li><li><strong>Service Workers:</strong> Implement service workers for caching and offline support.</li></ul><p><strong>Minification and Uglification</strong></p><ul><li>Minification removes unnecessary characters like whitespace and comments to reduce code file size.</li><li>While uglification is a more aggressive process that renames variables and functions to make the code unreadable and harder to reverse-engineer.</li></ul><p>Both techniques improve website performance by decreasing load times, but uglification’s primary purpose is often security protection through obfuscation.</p><p><strong>TrackBy with ngFor</strong></p><ul><li>Improves performance by avoiding re-rendering unchanged items.</li><li>By default, when the data source for an *ngFor loop changes (e.g., items are added, removed, or reordered), Angular re-renders all the DOM elements associated with the list.</li><li>This can be inefficient for large lists or frequent updates. trackBy uniquely identify each item in the list, allowing it to track changes more efficiently.</li></ul><pre>// app.component.ts<br>import { Component } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>})<br><br>export class AppComponent {<br>  products = [<br>    { id: 1, name: &#39;Laptop&#39; },<br>    { id: 2, name: &#39;Mouse&#39; },<br>    { id: 3, name: &#39;Keyboard&#39; },<br>  ];<br><br>  trackByProductId(index, product): number {<br>    return product.id;<br>  }<br><br>  // Example of modifying the list<br>  updateProducts(){<br>    this.products = [<br>      { id: 1, name: &#39;Laptop Pro&#39; }, // Modified existing item<br>      { id: 4, name: &#39;Monitor&#39; },    // Added new item<br>      { id: 3, name: &#39;Keyboard&#39; },<br>    ];<br>  }<br>}</pre><pre>&lt;!-- app.component.html --&gt;<br>&lt;ul&gt;<br>  &lt;li *ngFor=&quot;let product of products; trackBy: trackByProductId&quot;&gt;<br>    {{ product.name }}<br>  &lt;/li&gt;<br>&lt;/ul&gt;<br><br>&lt;button (click)=&quot;updateProducts()&quot;&gt;Update Products&lt;/button&gt;</pre><p><strong>How does Angular handle memory leaks, and what are some strategies to avoid them?</strong></p><p>Common Causes of Memory Leaks:</p><ol><li><strong>Unsubscribed Observables</strong>: If subscriptions to observables are not unsubscribed, it leads to memory leaks.<br> <strong>Solution</strong>: Use <strong>ngOnDestroy</strong> to unsubscribe or use the <strong>async pipe</strong>, which automatically handles subscriptions.</li><li><strong>Event Listeners</strong>: If event listeners are not cleaned up, they can cause memory leaks.<br> <strong>Solution</strong>: Use <strong>ngOnDestroy</strong> to remove event listeners or rely on Angular’s built-in <strong>Renderer2</strong> for safe DOM manipulation.</li><li><strong>Detached DOM Nodes</strong>: Keeping references to DOM elements outside of Angular’s change detection can cause memory leaks.<br> <strong>Solution</strong>: Always rely on Angular’s built-in directives and change detection mechanisms to manage DOM elements.</li><li><strong>Service Leaks</strong>: Services injected at the component level might hold unnecessary references if not disposed of correctly.<br> <strong>Solution</strong>: Use the <strong>providedIn</strong> syntax in services to ensure services are scoped correctly and do not hold unnecessary references.</li></ol><p><strong>Read More:</strong></p><ul><li><a href="https://dhilip-me.medium.com/angular-interview-preparation-db274264c3a1"><strong>Angular_Basics_Overview</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-lifecycle-hooks-mvvm-architecture-a6cca524ac09"><strong>Angular_Lifecycle_Hooks_And_MVVM_Architecture</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-synchronous-and-asynchronous-behaviors-3e1538f067b2"><strong>Angular_Synchronous_and_Asynchronous_Behaviors</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-pipes-6ccd97de6af1"><strong>Angular_Pipes</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/97941c37d897"><strong>Angular_Forms</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-router-586a84463179"><strong>Angular_Routing</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/angular-interceptors-1c918da59884"><strong>Angular_Interceptors</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-web-workers-1a41d79783d3"><strong>Angular_Web_Workers</strong></a></li><li><a href="https://dhilip-me.medium.com/rxjs-in-angular-63ae9902c4b7"><strong>RxJS_in_Angular</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/69d1fbf8a9fc"><strong>Operators_in_RxJS</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-application-optimization-1f59c0074c42"><strong>Angular_Application_Optimization</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/angular-scenario-based-interview-questions-991e8744fcac"><strong>Angular_Scenario_Based_Interview_Question</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f59c0074c42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Lifecycle Hooks & MVVM Architecture]]></title>
            <link>https://dhilip-me.medium.com/angular-lifecycle-hooks-mvvm-architecture-a6cca524ac09?source=rss-bc6e6d0c9eb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6cca524ac09</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[angular-lifecycle-hooks]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[mvvm-architecture]]></category>
            <category><![CDATA[mvvm]]></category>
            <dc:creator><![CDATA[Dhilip Kumar]]></dc:creator>
            <pubDate>Thu, 04 Dec 2025 07:54:04 GMT</pubDate>
            <atom:updated>2025-12-11T07:40:18.378Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What are Angular Lifecycle Hooks?</strong></p><p>Angular lifecycle hooks are methods that allows you to tap into key moments in a component’s lifecycle.</p><ol><li><strong>ngOnChanges()</strong>: Called whenever one or more data-bound input properties change. Receives a SimpleChanges object containing the current and previous property values.</li><li><strong>ngOnInit():</strong> Called once after the component is initialized.</li><li><strong>ngDoCheck():</strong> Called during every change detection cycle, immediately after ngOnChanges and ngOnInit, allowing you to implement your own change detection.</li><li><strong>ngAfterContentInit():</strong> Called once after Angular projects external content into the component’s view.</li><li><strong>ngAfterContentChecked():</strong> Called after every check of projected content.</li><li><strong>ngAfterViewInit():</strong> Called once after the component’s view and child views has been initialized.</li><li><strong>ngAfterViewChecked():</strong> Called after every check of the component’s view and child views.</li><li><strong>ngOnDestroy():</strong> Called just before Angular destroys the component, allowing you to clean up resources such as Unsubscribing from observables etc.</li></ol><pre>ngOnDestroy() {<br>  if (this.subscription) {<br>    this.subscription.unsubscribe();<br>  }<br>}</pre><p><strong>Explain the difference between ngOnInit() and constructor() in Angular</strong></p><p><strong>constructor()</strong>:</p><ul><li>Constructor is called when the class is instantiated (i.e., when the component is created).</li><li>Used for <strong>Dependency Injection (DI)</strong> and for <strong>initializing class members</strong>.</li></ul><p><strong>ngOnInit()</strong>:</p><ul><li>ngOnInit() is called once after the component is initialized after the constructor and it is used for <strong>initialization</strong> data.</li></ul><pre>constructor(private myService: MyService) {<br>  // Used for DI and setting up properties<br>}<br><br>ngOnInit(): void {<br>  // This is where you can fetch data or perform other initialization tasks<br>  this.fetchData();<br>}</pre><p><strong>What is MVVM architecture in Angular?</strong></p><p>A software architectural pattern that separates user interface (UI) from its business logic to improve code maintainability and testability.</p><p>It consists of three main components: the <strong>Model</strong> (data and business logic), the <strong>View</strong> (the UI), and the <strong>ViewModel</strong> (a bridge between the View and Model that contains presentation logic)</p><p><strong>Model:</strong></p><ul><li>Model represents the application’s data and business logic.</li><li>It is responsible for retrieving and storing data via APIs.</li></ul><p><strong>View:</strong></p><ul><li>View represents the UI and the elements that the user interacts with like buttons, inputs etc.</li><li>View is typically defined using HTML and CSS.</li></ul><p><strong>ViewModel:</strong></p><ul><li>ViewModel acts as a bridge, exposing data from the Model in a way that is easy for the View to consume.</li><li>It receives commands from the View (e.g., a button click) and uses them to interact with the Model, then updates the View by providing new data to it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/0*zXLUHx2Tv_RvEveS.png" /></figure><p><strong>Read More:</strong></p><ul><li><a href="https://dhilip-me.medium.com/angular-interview-preparation-db274264c3a1"><strong>Angular_Basics_Overview</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-lifecycle-hooks-mvvm-architecture-a6cca524ac09"><strong>Angular_Lifecycle_Hooks_And_MVVM_Architecture</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-synchronous-and-asynchronous-behaviors-3e1538f067b2"><strong>Angular_Synchronous_and_Asynchronous_Behaviors</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-pipes-6ccd97de6af1"><strong>Angular_Pipes</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/97941c37d897"><strong>Angular_Forms</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-router-586a84463179"><strong>Angular_Routing</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/angular-interceptors-1c918da59884"><strong>Angular_Interceptors</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-web-workers-1a41d79783d3"><strong>Angular_Web_Workers</strong></a></li><li><a href="https://dhilip-me.medium.com/rxjs-in-angular-63ae9902c4b7"><strong>RxJS_in_Angular</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/69d1fbf8a9fc"><strong>Operators_in_RxJS</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-application-optimization-1f59c0074c42"><strong>Angular_Application_Optimization</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/angular-scenario-based-interview-questions-991e8744fcac"><strong>Angular_Scenario_Based_Interview_Question</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6cca524ac09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RxJS in Angular]]></title>
            <link>https://dhilip-me.medium.com/rxjs-in-angular-63ae9902c4b7?source=rss-bc6e6d0c9eb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/63ae9902c4b7</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Dhilip Kumar]]></dc:creator>
            <pubDate>Wed, 03 Dec 2025 08:01:27 GMT</pubDate>
            <atom:updated>2025-12-12T06:31:48.164Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Can you explain the role of RxJs in Angular?</strong></p><ul><li>RxJS, stands for Reactive Extensions for JavaScript.</li><li>It is a library for reactive programming that uses Observables to handle asynchronous and event-based code.</li></ul><p><strong>What is reactive programming?</strong></p><p><strong>Reactive programming</strong> is a programming paradigm that deals with asynchronous data streams, that uses Observables to handle asynchronous and event-based code.</p><p><strong>What is imperative programming?</strong></p><p><strong>Imperative programming</strong> is a programming paradigm to achieve a result through a sequence of commands using statements, for loops, and conditions.</p><p>Popular imperative languages include C, Java, and Python.</p><p><strong>Core roles of RxJS in Angular,</strong></p><ol><li><strong>Asynchronous operations: </strong>HTTP requests are handled using the HttpClient module. It provides methods to perform RESTful operations like GET, POST, PUT, DELETE, etc. These requests return <strong>Observables</strong>, which can be subscribed to in components or services.</li><li><strong>Event handling:</strong> It is used to manage DOM events, like button clicks and form submissions.</li><li><strong>Form handling:</strong> It is used to manage form value changes in real-time and perform actions like validation and more.</li><li><strong>Real-time data:</strong> It is used to handle real-time data streams from sources like WebSockets.</li></ol><p>RxJS is the backbone of Angular’s asynchronous handling, providing tools for working with HTTP requests, events and form handling.</p><p><strong>How RxJS works?</strong></p><p>Based on Observables and operators.</p><ol><li><strong>Observables:</strong> An observable is a data stream that can emit multiple values over time. An observable can emit zero or more values before it completes or errors out. They only start producing values and executing their logic when an observer actively subscribes to them. Observables are lazy, can be cancelled anytime by unsubscribing.</li><li><strong>Operators:</strong> These are functions that work on Observables to transform, filter, combine, or manipulate the data they emit.</li></ol><ul><li><strong>Transformation:</strong> Operators like map() and switchMap() can change the shape of the data being emitted.</li><li><strong>Filtering:</strong> Operators like filter() allows you to select specific values from the stream.</li><li><strong>Error Handling:</strong> Operators like catchError() provide a way to handle errors in the stream without stopping the application.</li></ul><p><strong>What is an Observer ?</strong></p><ul><li>Observer is the consumer of the data stream provided by an Observable.</li><li>Observer defines the callbacks to be executed when an Observable emits values, errors, or completes.</li></ul><p><strong>What is a Promise ?</strong></p><ul><li><strong>Promise</strong> provides a structured way to handle asynchronous tasks, such as fetching data from a server or performing time-consuming calculations, without blocking the main thread of execution.</li><li>Promise is designed to emit a single value (either a successful result or an error) once its operation completes.</li></ul><p>A Promise can exist in one of three states:</p><ul><li><strong>Pending:</strong> The initial state; the operation is still in progress.</li><li><strong>Fulfilled (Resolved):</strong> The operation completed successfully, and a value is available.</li><li><strong>Rejected:</strong> The operation failed, and an error was encountered.</li></ul><p><strong>Difference between Observable and Promise ?</strong></p><p>Observables and Promises both used for handling asynchronous operations in Angular.</p><p><strong>Value Emission:</strong></p><ul><li><strong>Promise:</strong> Promise is designed to emit a single value (either a successful result or an error) once its operation completes.</li><li><strong>Observable:</strong> An observable is a data stream that can emit multiple values over time. An observable can emit zero or more values before it completes or errors out.</li></ul><p><strong>Laziness vs. Eagerness:</strong></p><ul><li><strong>Promises:</strong> Executes immediately upon creation.</li><li><strong>Observable:</strong> Lazy; They only start producing values and executing their logic when an observer actively subscribes to them.</li></ul><p><strong>Cancellation:</strong></p><ul><li><strong>Promise:</strong> Cannot be cancelled once initiated.</li><li><strong>Observable:</strong> Can be cancelled anytime by unsubscribing.</li></ul><p><strong>Promise Example:</strong></p><pre>import { Component } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-promise-example&#39;,<br>  template: `<br>    &lt;p&gt;Promise Value: {{ data }}&lt;/p&gt;<br>  `,<br>})<br><br>export class PromiseExampleComponent {<br>  data: string | undefined;<br><br>  ngOnInit() {<br>    this.fetchDataPromise()<br>      .then((result) =&gt; {<br>        this.data = result;<br>      })<br>      .catch((error) =&gt; {<br>        console.error(&#39;Error fetching data:&#39;, error);<br>      });<br>  }<br><br>  fetchDataPromise(): Promise&lt;string&gt; {<br>    return new Promise((resolve, reject) =&gt; {<br>      setTimeout(() =&gt; {<br>        const success = true; // Simulate success or failure<br>        if (success) {<br>          resolve(&#39;Data fetched successfully from Promise!&#39;);<br>        } else {<br>          reject(&#39;Failed to fetch data from Promise.&#39;);<br>        }<br>      }, 2000);<br>    });<br>  }<br>}</pre><p><strong>Observable Example:</strong></p><pre>import { HttpClient } from &#39;@angular/common/http&#39;;<br>import { Injectable } from &#39;@angular/core&#39;;<br>import { Observable } from &#39;rxjs&#39;;<br><br>@Injectable({<br>  providedIn: &#39;root&#39;,<br>})<br><br>export class UserService {<br>  constructor(private http: HttpClient) {}<br><br>  getUsers(){<br>    return this.http.get(&#39;/api/users&#39;); // Returns an Observable<br>  }<br>}</pre><pre>import { Component, OnInit } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-user-list&#39;,<br>  template: `<br>    &lt;ul&gt;<br>      &lt;li *ngFor=&quot;let user of users&quot;&gt;{{ user.name }}&lt;/li&gt;<br>    &lt;/ul&gt;<br>  `,<br>})<br><br>export class UserListComponent implements OnInit {<br>  users = [];<br><br>  constructor(private userService: UserService) {}<br><br>  ngOnInit(): void {<br>    this.userService.getUsers().subscribe((data) =&gt; {<br>      this.users = data;<br>    });<br>  }<br>}</pre><p><strong>Write a simple Observable that emits a sequence of numbers from 1 to 5 and completes.</strong></p><pre>import { range } from &#39;rxjs&#39;;<br><br>// Create an Observable that emits numbers from 1 to 5<br>const numbers$ = range(1, 5);<br><br>// Subscribe to the Observable to receive the emitted values<br>numbers$.subscribe({<br>  next: (value) =&gt; console.log(`Emitted value: ${value}`),<br>  error: (err) =&gt; console.error(`Error: ${err}`),<br>  complete: () =&gt; console.log(&#39;Observable completed&#39;),<br>});</pre><p><strong>What are Subjects?</strong></p><p>Subjects are special type of observable used to multicast values to multiple observers. Key differences include the following:</p><ul><li><strong>Subject:</strong> A basic multicast Observable.</li><li><strong>BehaviorSubject:</strong> Emits latest value to new subscribers and requires an initial value.</li><li><strong>ReplaySubject:</strong> Emits specified number of past values to new subscribers. Uses buffer to hold values and re-emits values on new subscriptions.</li><li><strong>AsyncSubject: </strong>Emits only the last value and only when the source Observable completes.</li></ul><p><strong>Subject and behaviorsubject in angular?</strong></p><p>Both Subject and BehaviorSubject are special types of Observables that allow multicasting. The key difference lies in how they handle the &quot;current&quot; value and initial values.</p><p><strong>Subject</strong></p><ul><li><strong>No Initial Value:</strong> A Subject does not require an initial value upon creation.</li><li><strong>No “Current” Value Retention:</strong> When a new subscriber subscribes to a Subject, it will only receive values emitted after the point of subscription. It does not retain or provide the last emitted value to new subscribers.</li><li><strong>Example:</strong> Imagine a live chat application using a Subject. If a user joins the chat, they will only see messages sent from that point forward, not the conversation history before they joined.</li></ul><pre>import { Subject } from &#39;rxjs&#39;;<br><br>const mySubject = new Subject&lt;string&gt;();<br><br>mySubject.subscribe(value =&gt; console.log(`Subscriber 1: ${value}`)); // Subscribes here<br><br>mySubject.next(&#39;First message&#39;); // Emits &#39;First message&#39;<br>mySubject.next(&#39;Second message&#39;); // Emits &#39;Second message&#39;<br><br>mySubject.subscribe(value =&gt; console.log(`Subscriber 2: ${value}`)); // Subscribes here<br><br>mySubject.next(&#39;Third message&#39;); // Emits &#39;Third message&#39;<br><br>// Output:<br>// Subscriber 1: First message<br>// Subscriber 1: Second message<br>// Subscriber 1: Third message<br>// Subscriber 2: Third message</pre><p><strong>BehaviorSubject</strong></p><ul><li><strong>Requires Initial Value: </strong>A BehaviorSubject must be initialized when created.</li><li><strong>Retains “Current” Value: </strong>It always holds the most recent value emitted to it. When a new subscriber subscribes to a BehaviorSubject, it immediately receives this current (or initial) value, and then all subsequent values.</li><li><strong>Example: </strong>BehaviorSubject could hold the current user&#39;s profile information. Any new component subscribing to this BehaviorSubject would immediately get the current profile data.</li></ul><pre>import { BehaviorSubject } from &#39;rxjs&#39;;<br><br>const myBehaviorSubject = new BehaviorSubject&lt;number&gt;(0); // Initial value is 0<br><br>myBehaviorSubject.subscribe(value =&gt; console.log(`Subscriber A: ${value}`)); // Subscribes here<br><br>myBehaviorSubject.next(1); // Emits 1<br>myBehaviorSubject.next(2); // Emits 2<br><br>myBehaviorSubject.subscribe(value =&gt; console.log(`Subscriber B: ${value}`)); // Subscribes here, immediately gets 2<br>myBehaviorSubject.next(3); // Emits 3<br><br>// Output:<br>// Subscriber A: 0<br>// Subscriber A: 1<br>// Subscriber A: 2<br>// Subscriber B: 2<br>// Subscriber A: 3<br>// Subscriber B: 3</pre><p><strong>BehaviorSubject code example</strong></p><p><strong>1. Setting a value:</strong> To set a value in a BehaviorSubject, use the next() method.</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { BehaviorSubject } from &#39;rxjs&#39;;<br><br>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br><br>export class DataService {<br>  private _myData = new BehaviorSubject&lt;string&gt;(&#39;Initial Data&#39;); // Initialize with a default value<br>  public myData$ = this._myData.asObservable(); // Expose as Observable to prevent external modification<br><br>  constructor() { }<br><br>  setData(newData: string) {<br>    this._myData.next(newData); // Set the new value<br>  }<br><br>  getData(){<br>    return this._myData.asObservable();<br>  }<br>}</pre><p><strong>2. Getting the current value: </strong>You can retrieve the current value of a BehaviorSubject directly using the getValue() method.</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { DataService } from &#39;./data.service&#39;;<br><br>@Component({<br>  selector: &#39;app-my-component&#39;,<br>  template: `&lt;p&gt;Current Data: {{ currentData }}&lt;/p&gt;`<br>})<br><br>export class MyComponent {<br>  currentData: string;<br><br>  constructor(private dataService: DataService) {<br>    this.currentData = this.dataService._myData.getValue(); // Access the BehaviorSubject directly for current value<br>  }<br>}</pre><p>Note: While you can access _myData.getValue(), it&#39;s generally recommended to expose myData$ as an Observable and subscribe to it for reactive updates, especially in templates using the async pipe.</p><p><strong>3. Subscribing to value changes:</strong></p><pre>import { Component, OnDestroy, OnInit } from &#39;@angular/core&#39;;<br>import { DataService } from &#39;./data.service&#39;;<br>import { Subscription } from &#39;rxjs&#39;;<br><br>@Component({<br>  selector: &#39;app-another-component&#39;,<br>  template: `&lt;p&gt;Received Data: {{ receivedData }}&lt;/p&gt;`<br>})<br><br>export class AnotherComponent implements OnInit, OnDestroy {<br>  receivedData: string;<br>  private dataSubscription: Subscription;<br><br>  constructor(private dataService: DataService) { }<br><br>  ngOnInit() {<br>    this.dataSubscription = this.dataService.myData$.subscribe(data =&gt; {<br>      this.receivedData = data; // Update when data changes<br>    });<br>    //or<br>    this.dataSubscription = this.dataService.getData().subscribe(data =&gt; {<br>      this.receivedData = data; // Update when data changes<br>    });<br>  }<br><br>  ngOnDestroy() {<br>    this.dataSubscription.unsubscribe(); // Prevent memory leaks<br>  }<br>}</pre><p><strong>What is the difference between BehaviorSubject and Observable in RxJS?</strong></p><ul><li>Observable is a consumer/listener while a BehaviourSubject is a synchronous data source that emits data to observers.</li><li>Observables are stateless while BehaviourSubject is stateful.</li><li>Observables create a copy of the data while BehaviourSubject emits data to observers.</li><li>Observables are unidirectional in nature while BehaviorSubject is bi-directional in nature.</li></ul><p><strong>What is multicasting?</strong></p><ul><li>Multicasting in Angular is achieved using RxJS Subjects</li><li>It allows a single execution of an Observable to be shared among multiple subscribers.</li><li>This prevents redundant work and ensures all subscribers receive the same values emitted by the source Observable.</li></ul><pre>observable$ = new Observable&lt;number&gt;(subscriber =&gt; {<br>  subscriber.next(Math.floor(Math.random() * 200) + 1);<br>});<br><br>subject$ = new Subject();<br><br>ngOnInit() {<br>  this.observable$.subscribe(val =&gt; {<br>    console.log(&quot;Obs1 :&quot; + val);<br>  });<br><br>  this.observable$.subscribe(val =&gt; {<br>    console.log(&quot;Obs2 :&quot; + val);<br>  });<br><br>  this.subject$.subscribe(val =&gt; {<br>    console.log(&quot;Sub1 &quot; + val);<br>  });<br><br>  this.subject$.subscribe(val =&gt; {<br>    console.log(&quot;Sub2 &quot; + val);<br>  });<br><br>  this.subject$.next(Math.floor(Math.random() * 200) + 1);<br>}<br>}</pre><pre>Obs1 :78<br>Obs2 :48<br>Sub1 169<br>Sub2 169</pre><p><a href="https://stackblitz.com/edit/angular-observable-subjects-multicast-vs-unicast?file=src%2Fapp%2Fapp.component.ts">https://stackblitz.com/edit/angular-observable-subjects-multicast-vs-unicast?file=src%2Fapp%2Fapp.component.ts</a></p><p><strong>Whats is Backpressure in RxJS and how it can be managed?</strong></p><ul><li>Backpressure is when a data producer sends data faster than a consumer can handle it.</li><li>Backpressure is handled by controlling the producer, buffering, or dropping data or using operators like debounceTime .</li></ul><p><strong>What is Higher-Order Observable Mapping?</strong></p><ul><li>Higher-order observable mapping is a technique where an observable emits another observable, rather than a simple value.</li><li>Achieved using <strong>higher-order mapping operators</strong> like switchMap, mergeMap, and concatMap, which subscribes to the inner observables and “flatten” them into a single, simpler stream of values.</li><li>Used for handling nested asynchronous operations, such as making a sequence of HTTP requests based on a previous result.</li></ul><p><strong>Cold observable vs Hot observable?</strong></p><ul><li>Cold observables start emitting values only when a subscriber subscribes to them, and each subscription gets its own independent execution of the observable.</li><li>Hot observables produce values before any subscription, and all subscribers share the same stream of data, it receives only the events that occur after they subscribe.</li><li>Common examples for cold observables — HTTP requests and for hot observables — user events like mouse movements or WebSocket data.</li></ul><p><strong>How do you create a hot Observable? Write a code snippet demonstrating this.</strong></p><pre>import { interval } from &#39;rxjs&#39;;<br>import { take, share } from &#39;rxjs/operators&#39;;<br><br>// Create a cold Observable that emits numbers every 1 second<br>const coldObservable = interval(1000).pipe(take(5));<br><br>// Make the cold Observable hot using the share() operator<br>const hotObservable = coldObservable.pipe(share());<br><br>console.log(&#39;Subscriber A subscribing...&#39;);<br>hotObservable.subscribe(value =&gt; console.log(`Subscriber A: ${value}`));<br><br>setTimeout(() =&gt; {<br>  console.log(&#39;Subscriber B subscribing after 2.5 seconds...&#39;);<br>  hotObservable.subscribe(value =&gt; console.log(`Subscriber B: ${value}`));<br>}, 2500);<br><br>setTimeout(() =&gt; {<br>  console.log(&#39;Subscriber C subscribing after 6 seconds...&#39;);<br>  hotObservable.subscribe(value =&gt; console.log(`Subscriber C: ${value}`));<br>}, 6000);</pre><ul><li>Subscriber A subscribes immediately and starts receiving values from the beginning of the interval.</li><li>Subscriber B subscribes after 2.5 seconds. Since hotObservable is already emitting, Subscriber B will receive values starting from the point of its subscription, sharing the same execution as Subscriber A. It will not receive the values emitted before its subscription.</li><li>Subscriber C subscribes after 6 seconds, after the coldObservable has completed (due to take(5)). Subscriber C will receive no values because the hot Observable has already completed its emissions.</li></ul><p><strong>How can you optimize RxJS operators to improve Angular app performance?</strong></p><ul><li>Utilize operators like <strong>debounceTime, distinctUntilChanged, and throttleTime</strong> to limit the frequency of emitted values.</li><li>Use <strong>buffer()</strong> to collect and emit values in batches.</li><li>Use <strong>share() or shareReplay()</strong> operators to share a single subscription among multiple subscribers.</li><li>Unsubscribe from Observables when they are no longer needed to prevent memory leaks.</li><li>Use the async pipe in templates to automatically manage subscriptions.</li></ul><p><strong>What are some best practices for error handling in RxJS?</strong></p><ol><li>Use the <strong>catchError</strong> operator to handle errors within the Observable pipeline.</li><li>Use the <strong>retry or retryWhen</strong> operators to retry failed operations.</li><li>Handle errors in the subscribe method’s error callback.</li></ol><p><strong>What are Schedulers:</strong></p><p>Scheduler controls the execution of when the subscription has to start and be notified.</p><p><strong>Types of schedulers</strong>: queueScheduler, asapScheduler, asyncScheduler, animationFrameScheduler</p><p><strong>queueScheduler: </strong>queueScheduler defers the tasks to the JavaScript event queue, ensuring they execute synchronously in a specific order.</p><pre>import { queueScheduler } from &#39;rxjs&#39;;<br><br>console.log(&#39;Start&#39;);<br><br>queueScheduler.schedule(() =&gt; {<br>  console.log(&#39;First task in queue&#39;);<br>  queueScheduler.schedule(() =&gt; {<br>    console.log(&#39;Second task in queue (scheduled from first)&#39;);<br>  });<br>});<br><br>queueScheduler.schedule(() =&gt; {<br>  console.log(&#39;Third task in queue (scheduled directly)&#39;);<br>});<br><br>console.log(&#39;End&#39;);</pre><pre>Start<br>End<br>First task in queue<br>Second task in queue (scheduled from first)<br>Third task in queue (scheduled directly)</pre><p><strong>asapScheduler: </strong>asapScheduler schedules tasks asynchronously but prioritizes them to execute as soon as possible after the current synchronously executing code finishes.</p><pre>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { asapScheduler, asyncScheduler } from &#39;rxjs&#39;;<br><br>@Component({<br>  selector: &#39;app-scheduler-example&#39;,<br>  template: `<br>    &lt;p&gt;Check the console for scheduler output.&lt;/p&gt;<br>  `,<br>})<br><br>export class SchedulerExampleComponent implements OnInit {<br><br>  ngOnInit(): void {<br><br>    console.log(&#39;Synchronous code starts&#39;);<br><br>    // Schedule a task with asyncScheduler<br>    asyncScheduler.schedule(() =&gt; {<br>      console.log(&#39;Async task (asyncScheduler)&#39;);<br>    });<br><br>    // Schedule a task with asapScheduler<br>    asapScheduler.schedule(() =&gt; {<br>      console.log(&#39;Async task (asapScheduler)&#39;);<br>    });<br><br>    console.log(&#39;Synchronous code ends&#39;);<br>  }<br>}</pre><pre>Synchronous code starts<br>Synchronous code ends<br>Async task (asapScheduler)<br>Async task (asyncScheduler)</pre><p><strong>asyncScheduler: </strong>asyncScheduler is used for scheduling asynchronous operations, involving time-based delays. It utilizes setTimeout internally to achieve this.</p><pre>import { asyncScheduler } from &#39;rxjs&#39;;<br><br>// Define the task to be executed<br>const myTask = () =&gt; {<br>  console.log(&#39;Task executed after a delay!&#39;);<br>};<br><br>// Schedule the task with a 2-second delay<br>asyncScheduler.schedule(myTask, 2000);</pre><p><strong>animationFrameScheduler: </strong>animationFrameScheduler is a specialized scheduler designed to perform tasks right before the browser&#39;s next content repaint. Used for creating smooth and efficient browser animations.</p><pre>// html: &lt;div style=&quot;background: #0ff;&quot;&gt;&lt;/div&gt;<br>import { animationFrameScheduler } from &quot;rxjs&quot;;<br><br>const div = document.querySelector(&quot;div&quot;);<br><br>// parameter (function, delay, state)<br>animationFrameScheduler.schedule(<br>  function(height) {<br>    div.style.height = height + &quot;px&quot;;<br>    this.schedule(height + 1); <br>    // `this` references currently executing Action,<br>    // which we reschedule with new state<br>  },<br>  0,<br>  200<br>);</pre><p><strong>What is Redux?</strong></p><p>Redux is a JavaScript library for managing an application’s state. Used in frontend framework such as React, Angular &amp; Rxjs.</p><p><strong>What are the core principles of Redux?</strong></p><ul><li><strong>Single source of Truth</strong>: All application data is stored in a single object tree.</li><li><strong>State is read only</strong>: The state is immutable.</li><li><strong>State can only be change with Pure Functions</strong>: These pure functions are called <strong>Reduces</strong> and they specify how the object tree should be updated.</li></ul><p><strong>Is there any similarity between Redux and RxJS?</strong></p><ul><li>Redux uses reactive paradigm to mutate state of the store.</li><li>RxJs uses reactive paradigm to accomplish asynchronous data processing.</li></ul><p><strong>Read More:</strong></p><ul><li><a href="https://dhilip-me.medium.com/angular-interview-preparation-db274264c3a1"><strong>Angular_Basics_Overview</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-lifecycle-hooks-mvvm-architecture-a6cca524ac09"><strong>Angular_Lifecycle_Hooks_And_MVVM_Architecture</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-synchronous-and-asynchronous-behaviors-3e1538f067b2"><strong>Angular_Synchronous_and_Asynchronous_Behaviors</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-pipes-6ccd97de6af1"><strong>Angular_Pipes</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/97941c37d897"><strong>Angular_Forms</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-router-586a84463179"><strong>Angular_Routing</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/angular-interceptors-1c918da59884"><strong>Angular_Interceptors</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-web-workers-1a41d79783d3"><strong>Angular_Web_Workers</strong></a></li><li><a href="https://dhilip-me.medium.com/rxjs-in-angular-63ae9902c4b7"><strong>RxJS_in_Angular</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/69d1fbf8a9fc"><strong>Operators_in_RxJS</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-application-optimization-1f59c0074c42"><strong>Angular_Application_Optimization</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/angular-scenario-based-interview-questions-991e8744fcac"><strong>Angular_Scenario_Based_Interview_Question</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63ae9902c4b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Synchronous and Asynchronous Behaviors]]></title>
            <link>https://dhilip-me.medium.com/angular-synchronous-and-asynchronous-behaviors-3e1538f067b2?source=rss-bc6e6d0c9eb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e1538f067b2</guid>
            <category><![CDATA[synchronous]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[async]]></category>
            <dc:creator><![CDATA[Dhilip Kumar]]></dc:creator>
            <pubDate>Wed, 03 Dec 2025 07:47:46 GMT</pubDate>
            <atom:updated>2025-12-11T07:44:40.995Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>How do you handle HTTP requests in Angular?</strong></p><ul><li>HTTP requests are handled using the HttpClient module.</li><li>It provides methods to perform RESTful operations like GET, POST, PUT, DELETE, etc.</li><li>These requests return <strong>Observables</strong>, which can be subscribed in components or services.</li></ul><p>Steps to Handle HTTP Requests:</p><p>1.<strong>Import HttpClientModule</strong>: You need to import the HttpClientModule in the application module (app.module.ts).</p><pre>import { HttpClientModule } from &#39;@angular/common/http&#39;;<br><br>@NgModule({<br>  declarations: [AppComponent],<br>  imports: [HttpClientModule],<br>  bootstrap: [AppComponent]<br>})<br><br>export class AppModule {}</pre><p>2.<strong>Inject HttpClient in Service</strong>: Create a service where HTTP requests are made and inject HttpClient into the service’s constructor.</p><pre>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br><br>export class UserService {<br>  private apiUrl = &#39;https://api.example.com/users&#39;;<br><br>  constructor(private http: HttpClient) {}<br><br>  getUsers() {<br>    return this.http.get(this.apiUrl);<br>  }<br><br>  addUser(user: any) {<br>    return this.http.post(this.apiUrl, user);<br>  }<br>}</pre><p>3.<strong>Subscribe to the Observable</strong>: In the component, call the service method and subscribe to the Observable to get the response.</p><pre>@Component({<br>  selector: &#39;app-user-list&#39;,<br>  template: `&lt;ul&gt;&lt;li *ngFor=&quot;let user of users&quot;&gt;{{ user.name }}&lt;/li&gt;&lt;/ul&gt;`<br>})<br><br>export class UserListComponent {<br>  users: any[];<br><br>  constructor(private userService: UserService) {}<br><br>  ngOnInit() {<br>    this.userService.getUsers().subscribe(users =&gt; this.users = users);<br>  }<br>}</pre><p>4.<strong>Error Handling</strong>: Use the catchError operator to handle errors.</p><pre>import { catchError } from &#39;rxjs/operators&#39;;<br>import { of } from &#39;rxjs&#39;;<br><br>getUsers() {<br>  return this.http.get(this.apiUrl).pipe(<br>    catchError(error =&gt; {<br>      console.error(&#39;Error fetching users:&#39;, error);<br>      return of([]);  // Return empty array in case of error<br>    })<br>  );<br>}</pre><p><strong>Explain Synchronous and asynchronous</strong></p><ul><li><strong>Synchronous</strong> operations happen in a sequence, where one task must complete before the next can begin.</li><li><strong>Asynchronous</strong> operations can occur independently, allowing subsequent tasks to start before previous ones finish.</li></ul><p><strong>Synchronous API Calls:</strong></p><ul><li><strong>Blocking behavior: </strong>When a synchronous API call is made, the calling program “blocks” or pauses its execution until it receives a response from the API. No other tasks can be performed during this waiting period.</li><li><strong>Sequential processing: </strong>Requests are processed one after another. If a request takes long time, it can cause the entire application to appear unresponsive.</li><li><strong>Simplicity: </strong>Easy to implement due to their linear execution flow.</li><li><strong>Use cases: </strong>Suitable for tasks requiring immediate feedback such as User Authentication.</li></ul><p><strong>Asynchronous API Calls:</strong></p><ul><li><strong>Non-blocking behavior: </strong>When an asynchronous API call is made, the calling program does not wait for a response. It continues executing other tasks while the API call is processed in the background.</li><li><strong>Concurrent processing: </strong>Multiple requests can be initiated and processed concurrently.</li><li><strong>Complexity: </strong>Callbacks, promises are required to handle the response when it arrives, making the implementation complex.</li><li><strong>Use cases: </strong>Ideal for long-running tasks, where immediate feedback is not essential, such as fetching data from a slow external service.</li></ul><p>async/await simplifies asynchronous, non-blocking code to behave like synchronous code.</p><ul><li>The async keyword ensures the function returns a promise.</li><li>And the await keyword pauses the execution of the function until a promise settles.</li></ul><p><strong>Asynchronous API Call Example (Standard Angular approach):</strong></p><p>This example demonstrates a typical asynchronous API call using HttpClient and subscribing to the Observable.</p><pre>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;<br>import { Observable } from &#39;rxjs&#39;;<br><br>interface Todo {<br>  userId: number;<br>  id: number;<br>  title: string;<br>  completed: boolean;<br>}<br><br>@Component({<br>  selector: &#39;app-async-example&#39;,<br>  template: `<br>    &lt;h2&gt;Asynchronous API Call&lt;/h2&gt;<br>    &lt;div *ngIf=&quot;todo&quot;&gt;<br>      &lt;p&gt;Title: {{ todo.title }}&lt;/p&gt;<br>      &lt;p&gt;Completed: {{ todo.completed }}&lt;/p&gt;<br>    &lt;/div&gt;<br>    &lt;p&gt;This message appears immediately after the API call is initiated.&lt;/p&gt;<br>  `,<br>})<br><br>export class AsyncExampleComponent implements OnInit {<br>  todo: Todo | undefined;<br><br>  constructor(private http: HttpClient) {}<br><br>  ngOnInit(): void {<br>    this.fetchDataAsync().subscribe(data =&gt; {<br>      this.todo = data;<br>      console.log(&#39;Data received asynchronously:&#39;, this.todo);<br>    });<br>    console.log(&#39;API call initiated.&#39;);<br>  }<br><br>  fetchDataAsync(): Observable&lt;Todo&gt; {<br>    return this.http.get&lt;Todo&gt;(&#39;https://jsonplaceholder.typicode.com/todos/1&#39;);<br>  }<br>}</pre><p><strong>Synchronous-like API Call Example (using </strong><strong>async/await):</strong></p><p>This example uses async/await to make the asynchronous API call appear sequential in its execution within the fetchDataSync method.</p><pre>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;<br><br>interface Todo {<br>  userId: number;<br>  id: number;<br>  title: string;<br>  completed: boolean;<br>}<br><br>@Component({<br>  selector: &#39;app-sync-example&#39;,<br>  template: `<br>    &lt;h2&gt;Synchronous-like API Call (using async/await)&lt;/h2&gt;<br>    &lt;div *ngIf=&quot;todo&quot;&gt;<br>      &lt;p&gt;Title: {{ todo.title }}&lt;/p&gt;<br>      &lt;p&gt;Completed: {{ todo.completed }}&lt;/p&gt;<br>    &lt;/div&gt;<br>    &lt;p&gt;This message appears after the API call completes and data is available.&lt;/p&gt;<br>  `,<br>})<br><br>export class SyncExampleComponent implements OnInit {<br>  todo: Todo | undefined;<br><br>  constructor(private http: HttpClient) {}<br><br>  async ngOnInit(): Promise&lt;void&gt; {<br>    await this.fetchDataSync();<br>    console.log(&#39;API call completed and data processed.&#39;);<br>  }<br><br>  async fetchDataSync(): Promise&lt;void&gt; {<br>    try {<br>      // Convert the Observable to a Promise for use with await<br>      const data = await this.http.get&lt;Todo&gt;(&#39;https://jsonplaceholder.typicode.com/todos/1&#39;).toPromise();<br>      this.todo = data;<br>      console.log(&#39;Data received synchronously (within async function):&#39;, this.todo);<br>    } catch (error) {<br>      console.error(&#39;Error fetching data:&#39;, error);<br>    }<br>  }<br>}</pre><p>Here, fetchDataSync() is an async function. The await keyword pauses the execution of fetchDataSync until the toPromise() resolves, making the subsequent code appear to run synchronously after the data is fetched. The console.log(&#39;API call completed and data processed.&#39;) in ngOnInit will only execute after fetchDataSync finishes.</p><p><strong>Read More:</strong></p><ul><li><a href="https://dhilip-me.medium.com/angular-interview-preparation-db274264c3a1"><strong>Angular_Basics_Overview</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-lifecycle-hooks-mvvm-architecture-a6cca524ac09"><strong>Angular_Lifecycle_Hooks_And_MVVM_Architecture</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-synchronous-and-asynchronous-behaviors-3e1538f067b2"><strong>Angular_Synchronous_and_Asynchronous_Behaviors</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-pipes-6ccd97de6af1"><strong>Angular_Pipes</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/97941c37d897"><strong>Angular_Forms</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-router-586a84463179"><strong>Angular_Routing</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/angular-interceptors-1c918da59884"><strong>Angular_Interceptors</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-web-workers-1a41d79783d3"><strong>Angular_Web_Workers</strong></a></li><li><a href="https://dhilip-me.medium.com/rxjs-in-angular-63ae9902c4b7"><strong>RxJS_in_Angular</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/69d1fbf8a9fc"><strong>Operators_in_RxJS</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-application-optimization-1f59c0074c42"><strong>Angular_Application_Optimization</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/angular-scenario-based-interview-questions-991e8744fcac"><strong>Angular_Scenario_Based_Interview_Question</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e1538f067b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Web Workers]]></title>
            <link>https://dhilip-me.medium.com/angular-web-workers-1a41d79783d3?source=rss-bc6e6d0c9eb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a41d79783d3</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[webworker]]></category>
            <category><![CDATA[web-workers-in-javascript]]></category>
            <category><![CDATA[javascript-web-worker]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Dhilip Kumar]]></dc:creator>
            <pubDate>Tue, 02 Dec 2025 07:54:45 GMT</pubDate>
            <atom:updated>2025-12-12T05:48:56.271Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What are the benefits of using Web Workers in Angular?</strong></p><ul><li><strong>Improved Performance:</strong> It allows offloading heavy computation tasks to background threads, freeing the main thread.</li><li><strong>Enhanced User Experience:</strong> By running complex operations in the background, Web Workers prevent the UI from becoming unresponsive.</li><li><strong>Parallel Processing:</strong> Web Workers enable parallel processing of tasks, which can speed up operations involving large datasets.</li><li><strong>Better Scalability:</strong> By distributing the workload</li></ul><ol><li><strong>Generate the Web Worker 🛠️</strong></li></ol><p>Use the Angular CLI to generate the necessary files for a web worker, for instance, next to your main AppComponent:</p><pre>ng generate web-worker app</pre><p>This command performs several actions:</p><ul><li>Creates a worker script file: src/app/app.worker.ts.</li><li>Updates project configuration files (angular.json, and creates tsconfig.worker.json).</li></ul><p><strong>angular.json</strong></p><pre>&quot;build&quot;: {<br>          &quot;builder&quot;: &quot;@angular-devkit/build-angular:browser&quot;,<br>          &quot;options&quot;: {<br>            &quot;outputPath&quot;: &quot;dist/web-worker&quot;,<br>            &quot;index&quot;: &quot;src/index.html&quot;,<br>            &quot;main&quot;: &quot;src/main.ts&quot;,<br>            &quot;polyfills&quot;: &quot;src/polyfills.ts&quot;,<br>            &quot;tsConfig&quot;: &quot;tsconfig.app.json&quot;,<br>            &quot;aot&quot;: true,<br>            &quot;assets&quot;: [<br>              &quot;src/favicon.ico&quot;,<br>              &quot;src/assets&quot;<br>            ],<br>            &quot;styles&quot;: [<br>              &quot;src/styles.css&quot;<br>            ],<br>            &quot;scripts&quot;: [],<br>            &quot;webWorkerTsConfig&quot;: &quot;tsconfig.worker.json&quot;<br>          },<br>          &quot;configurations&quot;: {<br>            &quot;production&quot;: {<br>              &quot;fileReplacements&quot;: [<br>                {<br>                  &quot;replace&quot;: &quot;src/environments/environment.ts&quot;,<br>                  &quot;with&quot;: &quot;src/environments/environment.prod.ts&quot;<br>                }<br>              ],<br>              &quot;optimization&quot;: true,<br>              &quot;outputHashing&quot;: &quot;all&quot;,<br>              &quot;sourceMap&quot;: false,<br>              &quot;extractCss&quot;: true,<br>              &quot;namedChunks&quot;: false,<br>              &quot;extractLicenses&quot;: true,<br>              &quot;vendorChunk&quot;: false,<br>              &quot;buildOptimizer&quot;: true,<br>              &quot;budgets&quot;: [<br>                {<br>                  &quot;type&quot;: &quot;initial&quot;,<br>                  &quot;maximumWarning&quot;: &quot;2mb&quot;,<br>                  &quot;maximumError&quot;: &quot;5mb&quot;<br>                },<br>                {<br>                  &quot;type&quot;: &quot;anyComponentStyle&quot;,<br>                  &quot;maximumWarning&quot;: &quot;6kb&quot;,<br>                  &quot;maximumError&quot;: &quot;10kb&quot;<br>                }<br>              ]<br>            }<br>          }<br>        },</pre><pre>&quot;lint&quot;: {<br>          &quot;builder&quot;: &quot;@angular-devkit/build-angular:tslint&quot;,<br>          &quot;options&quot;: {<br>            &quot;tsConfig&quot;: [<br>              &quot;tsconfig.app.json&quot;,<br>              &quot;tsconfig.spec.json&quot;,<br>              &quot;e2e/tsconfig.json&quot;,<br>              &quot;tsconfig.worker.json&quot;<br>            ],<br>            &quot;exclude&quot;: [<br>              &quot;**/node_modules/**&quot;<br>            ]<br>          }<br>        },</pre><p><strong>tsconfig.worker.json</strong></p><pre>{<br>  &quot;extends&quot;: &quot;./tsconfig.json&quot;,<br>  &quot;compilerOptions&quot;: {<br>    &quot;outDir&quot;: &quot;./out-tsc/worker&quot;,<br>    &quot;lib&quot;: [<br>      &quot;es2018&quot;,<br>      &quot;webworker&quot;<br>    ],<br>    &quot;types&quot;: []<br>  },<br>  &quot;include&quot;: [<br>    &quot;src/**/*.worker.ts&quot;<br>  ]<br>}</pre><ul><li>Adds scaffold code to both app.component.ts and app.worker.ts</li></ul><p><strong>2. Define the Worker Logic (</strong><strong>app.worker.ts)</strong></p><p>The worker script listens for messages from the main thread, performs a task, and posts a response back.</p><p>In this example, let’s create a CPU-intensive function, like calculating the Fibonacci number.</p><pre>// app.worker.ts<br>/// &lt;reference lib=&quot;webworker&quot; /&gt;<br><br>// The heavy task: recursive Fibonacci calculation<br>function calculateFibonacci(num: number): number {<br>  if (num &lt;= 1) return num;<br>  return calculateFibonacci(num - 1) + calculateFibonacci(num - 2);<br>}<br><br>// Listen for the message from the main thread<br>addEventListener(&#39;message&#39;, ({ data }) =&gt; {<br>  console.log(&#39;Worker: Starting heavy calculation...&#39;);<br>  <br>  // Perform the task<br>  const result = calculateFibonacci(data);<br>  <br>  // Send the result back to the main thread<br>  postMessage(result); <br>});</pre><p><strong>3. Implement the Worker in a Component (</strong><strong>app.component.ts)</strong></p><p>In your component, you’ll create an instance of the Worker, send data to it using postMessage(), and listen for the result using onmessage.</p><pre>// app.component.ts<br>import { Component } from &#39;@angular/core&#39;;<br><br>// --- Heavy Task Function (Used for Blocking Example Only) ---<br>// This function runs on the main thread when called directly.<br>const calculateFibonacci = (num: number): number =&gt; {<br>  if (num &lt;= 1) return num;<br>  return calculateFibonacci(num - 1) + calculateFibonacci(num - 2);<br>};<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.css&#39;]<br>})<br><br>export class AppComponent {<br>  fibNumber: number = 45;<br><br>  // Blocking State<br>  blockingResult: number | string = &#39;Ready&#39;;<br>  blockingTime: number | string = &#39;0&#39;;<br><br>  // Worker State<br>  workerResult: number | string = &#39;Ready&#39;;<br>  workerTime: number | string = &#39;0&#39;;<br><br>  // ------------------------------------------------------------------<br>  // 1. Implementation WITHOUT Web Worker (Blocking)<br>  // ------------------------------------------------------------------<br>  startBlockingTask() {<br>    this.blockingResult = &#39;Calculating...&#39;;<br>    this.blockingTime = &#39;...&#39;;<br><br>    const startTime = performance.now();<br>    <br>    // Call the heavy function directly on the main UI thread.<br>    const result = calculateFibonacci(this.fibNumber); <br>    <br>    const endTime = performance.now();<br><br>    this.blockingResult = result;<br>    this.blockingTime = (endTime - startTime).toFixed(2);<br>  }<br><br>  // ------------------------------------------------------------------<br>  // 2. Implementation WITH Web Worker (Non-Blocking)<br>  // ------------------------------------------------------------------<br>  startWorkerTask() {<br>    this.workerResult = &#39;Calculating...&#39;;<br>    this.workerTime = &#39;...&#39;;<br><br>    if (typeof Worker === &#39;undefined&#39;) {<br>      this.workerResult = &#39;Workers not supported.&#39;;<br>      return;<br>    }<br><br>    const startTime = performance.now();<br>    <br>    // Instantiate the worker using the URL path to the separate worker file.<br>    const worker = new Worker(&#39;./app.worker&#39;, { type: &#39;module&#39; });<br><br>    // Set up the listener for the worker&#39;s result<br>    worker.onmessage = ({ data }) =&gt; {<br>      const endTime = performance.now();<br>      <br>      this.workerResult = data;<br>      this.workerTime = (endTime - startTime).toFixed(2);<br>      <br>      // Cleanup: Terminate the worker<br>      worker.terminate();<br>    };<br><br>    // Send data to the worker to start the task<br>    worker.postMessage(this.fibNumber);<br>  }<br>}</pre><pre>&lt;h2&gt;Web Worker Comparison&lt;/h2&gt;<br>&lt;p&gt;Target N for Fibonacci: <br>    &lt;input type=&quot;number&quot; [(ngModel)]=&quot;fibNumber&quot; min=&quot;1&quot; max=&quot;45&quot;&gt;<br>&lt;/p&gt;<br><br>&lt;div style=&quot;display: flex; justify-content: space-around; margin-top: 20px;&quot;&gt;<br>    <br>    &lt;div style=&quot;padding: 15px; border: 1px solid red; width: 45%;&quot;&gt;<br>    &lt;h3&gt;🛑 Blocking UI (No Worker)&lt;/h3&gt;<br>    &lt;button (click)=&quot;startBlockingTask()&quot;&gt;Run Blocking Task&lt;/button&gt;<br>    &lt;p&gt;Result: **{{ blockingResult }}**&lt;/p&gt;<br>    &lt;p&gt;Time Taken: {{ blockingTime }}ms&lt;/p&gt;<br>    &lt;p style=&quot;color: red;&quot;&gt;⚠️ UI **freezes** until calculation is done.&lt;/p&gt;<br>    &lt;/div&gt;<br><br>    &lt;div style=&quot;padding: 15px; border: 1px solid green; width: 45%;&quot;&gt;<br>    &lt;h3&gt;✅ Responsive UI (Separate Worker)&lt;/h3&gt;<br>    &lt;button (click)=&quot;startWorkerTask()&quot;&gt;Run Worker Task&lt;/button&gt;<br>    &lt;p&gt;Result: **{{ workerResult }}**&lt;/p&gt;<br>    &lt;p&gt;Time Taken: {{ workerTime }}ms&lt;/p&gt;<br>    &lt;p style=&quot;color: green;&quot;&gt;✨ UI **stays responsive** during calculation.&lt;/p&gt;<br>    &lt;/div&gt;<br><br>&lt;/div&gt;</pre><p><a href="https://stackblitz.com/~/github.com/dhilip-me/web-worker">https://stackblitz.com/~/github.com/dhilip-me/web-worker</a></p><p><strong>Read More:</strong></p><ul><li><a href="https://dhilip-me.medium.com/angular-interview-preparation-db274264c3a1"><strong>Angular_Basics_Overview</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-lifecycle-hooks-mvvm-architecture-a6cca524ac09"><strong>Angular_Lifecycle_Hooks_And_MVVM_Architecture</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-synchronous-and-asynchronous-behaviors-3e1538f067b2"><strong>Angular_Synchronous_and_Asynchronous_Behaviors</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-pipes-6ccd97de6af1"><strong>Angular_Pipes</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/97941c37d897"><strong>Angular_Forms</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-router-586a84463179"><strong>Angular_Routing</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/angular-interceptors-1c918da59884"><strong>Angular_Interceptors</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-web-workers-1a41d79783d3"><strong>Angular_Web_Workers</strong></a></li><li><a href="https://dhilip-me.medium.com/rxjs-in-angular-63ae9902c4b7"><strong>RxJS_in_Angular</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/69d1fbf8a9fc"><strong>Operators_in_RxJS</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-application-optimization-1f59c0074c42"><strong>Angular_Application_Optimization</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/angular-scenario-based-interview-questions-991e8744fcac"><strong>Angular_Scenario_Based_Interview_Question</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a41d79783d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Routing]]></title>
            <link>https://dhilip-me.medium.com/angular-router-586a84463179?source=rss-bc6e6d0c9eb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/586a84463179</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[router]]></category>
            <category><![CDATA[routing]]></category>
            <category><![CDATA[angular-routing]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Dhilip Kumar]]></dc:creator>
            <pubDate>Tue, 02 Dec 2025 07:45:10 GMT</pubDate>
            <atom:updated>2025-12-12T05:37:10.150Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>How does Angular handle routing?</strong></p><ul><li>Angular routing is powered by @angular/router library. It manages navigation between different views without requiring full page reloads using Routes definition, Router outlet and Router Link.</li><li>It allows developers to define routes, handle URL changes, and load components dynamically.</li></ul><p><strong>What is difference between </strong><strong>Route and </strong><strong>Routes?</strong></p><p><strong>Route</strong>: Route is a configuration object that defines single route.</p><pre>{ path: &#39;manage-user&#39;, component: ManageUserComponent } </pre><p><strong>Routes</strong>: Routes is the set of Route.</p><pre>const routes: Routes = [<br> { path: &#39;manage-user&#39;, component: ManageUserComponent },<br> { path: &#39;update-user/:id&#39;, component: UpdateUserComponent }<br>]</pre><p><strong>Routes Configuration</strong>: Routes are defined in a <strong>routing module</strong> (typically app-routing.module.ts), where URL paths map to specific components.</p><p><strong>What is </strong><strong>&lt;router-outlet&gt;?</strong></p><p>The &lt;router-outlet&gt; acts as a placeholder that is filled dynamically based on the current router state. It marks the location where the router displays the view.</p><p><strong>What is RouterLink?</strong></p><p><strong>RouterLink </strong>binds the route with clickable HTML element such as anchor tag. And <strong>RouterLinkActive </strong>is a directive that binds the CSS class with HTML element and becomes active only when that element is clicked.</p><pre>&lt;a routerLink=&quot;/manage-user&quot; routerLinkActive=&quot;active-link&quot;&gt;Manage User&lt;/a&gt; </pre><p><strong>Example:</strong></p><p>1.Define routes in app-routing.module.ts:</p><pre>const routes: Routes = [<br>  { path: &#39;home&#39;, component: HomeComponent },<br>  { path: &#39;about&#39;, component: AboutComponent }<br>];</pre><p>2.Import RouterModule in AppModule:</p><pre>@NgModule({<br>  imports: [RouterModule.forRoot(routes)],<br>  exports: [RouterModule]<br>})<br><br>export class AppRoutingModule {}</pre><p>3.Use routerLink in templates:</p><pre>&lt;a routerLink=&quot;/home&quot;&gt;Home&lt;/a&gt;<br>&lt;a routerLink=&quot;/about&quot;&gt;About&lt;/a&gt;<br><br>&lt;router-outlet&gt;&lt;/router-outlet&gt; <br>&lt;!-- Routed component will be inserted here --&gt;</pre><p><strong>What are the main components of Angular routing?</strong></p><ul><li>Router</li><li>Routes</li><li>RouterOutlet</li><li>RouterLink</li></ul><p><strong>What is named router outlet and how is it created?</strong></p><ul><li>Named router outlet is used to open components in popup view.</li><li>Named outlet stays open even when we switch between pages in our application.</li><li>Named outlet is created using &lt;router-outlet&gt; tag with name attribute.</li></ul><pre>&lt;router-outlet name=&quot;userPopup&quot;&gt;&lt;/router-outlet&gt; </pre><p>To open a component in named outlet, find the path configuration.</p><pre>{<br>   path: &#39;update-user&#39;,<br>   component: UserUpdateComponent,<br>   outlet: &#39;userPopup&#39;<br>}</pre><p>Navigation:</p><pre>&lt;a [routerLink]=&quot;[{ outlets: { userPopup: [&#39;update-user&#39;] } }]&quot; &gt; </pre><p>To close a named outlet, pass route as null.</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { Router } from &#39;@angular/router&#39;;<br><br>@Component({<br>  selector: &#39;app-my-component&#39;,<br>  template: `<br>    &lt;button (click)=&quot;closeOutlet()&quot;&gt;Close Outlet&lt;/button&gt;<br>  `,<br>})<br>export class MyComponent {<br>  constructor(private router: Router) {}<br><br>  closeOutlet() {<br>    this.router.navigate([{ outlets: { userPopup: null } }]);<br>  }<br>}</pre><p><strong>What is the role of </strong><strong>RouterModule.forRoot() method ?</strong></p><p>This method is used to configure the router with routes and navigation-related settings at the application’s root level</p><pre>const routes: Routes = [<br> { path: &#39;home&#39;, component: HomeComponent },<br> { path: &#39;user-detail/:id&#39;, component: UserDetailComponent }  <br>];<br><br>@NgModule({<br>  imports: [ RouterModule.forRoot(routes) ],<br>  exports: [ RouterModule ]<br>})<br><br>export class AppRoutingModule{ }</pre><p><strong>How can you redirect a URL to another URL?</strong></p><p>Using redirectTo property.</p><pre>{ path: ‘’, redirectTo: ‘/dashboard’, pathMatch: &#39;full&#39; } </pre><p>For blank path, URL is redirected to <strong>/dashboard</strong> path.</p><p><strong>How can you handle ‘404 Not Found’ ?</strong></p><p>By using <strong>**</strong> in route path and associate a component with this path. (<strong>Wildcard route)</strong></p><pre>{ path: &#39;**&#39;, component: NotFound404Component } </pre><p>If given path has no mapping defined in module, then NotFound404Component will be executed.</p><p><strong>What is the purpose of Wildcard route?</strong></p><p>If the URL doesn’t match any predefined routes it will cause the router to throw an error and crash the app. In this case, we use wildcard route. A path with ** to match every URL.</p><pre>{ path: &#39;**&#39;, component: PageNotFoundComponent }</pre><p><strong>How will you create route path with parameters and access its values? (Path params)</strong></p><p>We’ll create a route path with parameters using colon <strong>(:)</strong></p><pre>{ path: &#39;get-user/:id&#39;, component: UserComponent } </pre><p>For the URL <strong>/get-user/100</strong>, the UserComponent will be invoked. The value for <strong>id</strong> will be 100. To fetch the value of <strong>id</strong> in UserComponent, use ActivatedRoute and Params.</p><pre>export class UpdateBookComponent implements OnInit {<br>    user;<br><br>    constructor(private route: ActivatedRoute,<br>        private userService: UserService,<br>        private location: Location) { }<br><br>    ngOnInit(): void {<br>        this.route.params.pipe(<br>            switchMap((params: Params) =&gt; this.userService.getUser(+params[&#39;id&#39;]))<br>        ).subscribe(user =&gt; this.user = user);<br><br>        //const id=+this.route.snapshot.paramMap.get(&#39;id&#39;);<br>        //console.log(&quot;id: &quot;+id);<br>    }<br>}</pre><ul><li><strong>ActivatedRoute</strong> : Contains route specific information such as route parameters, query params etc.</li><li><strong>Params</strong> : Contains the parameter value.</li></ul><p><strong>What is the role of Angular </strong><strong>Location service?</strong></p><p>The Location service is used to navigate back and forward.</p><pre>export class UserDetailComponent {<br><br>    constructor(private location: Location) { }<br><br>    goBack(){<br>        this.location.back();<br>    }<br><br>    goForward(){<br>        this.location.forward();<br>    }<br>}</pre><p><strong>How will you navigate from one component path to another component path programmatically?</strong></p><p>Using Router.navigate() method.</p><pre>{ path: &#39;update-user/:id&#39;, component: UpdateUserComponent } </pre><pre>export class UserDetailComponent {<br>    constructor(private router: Router) { }<br>    updateUser(id: number) {<br>        this.router.navigate([‘/update-user’, id]);<br>    }<br>}</pre><p><strong>How will you create children path?</strong></p><p>Using Route.children property.</p><pre>const userRoutes: Routes = [{ <br>       path: ‘dashboard’,<br>       component: DashboardComponent,<br>       children: [{<br>             path: &#39;add&#39;,<br>             component: AddUserComponent<br>       }]<br>}]</pre><p>The path <strong>/dashboard/add</strong> will invoke AddUserComponent.</p><p><strong>What is empty child route?</strong></p><p>An empty child route refers to a child route configuration where the path property is set to an empty string (&#39;&#39;).</p><pre>const userRoutes: Routes = [{ <br>      path: ‘dashboard’,<br>      component: DashboardComponent,<br>      children: [{<br>             path: &#39;&#39;,<br>             component: UserDetailComponent<br>      },<br>      { path: &#39;child1&#39;, component: ChildOneComponent }<br>      ]<br>}]</pre><p>For the path <strong>/dashboard</strong>, the component <strong>DashboardComponent -&gt; UserDetailComponent</strong> will be invoked.</p><p><strong>In how many ways is a module loaded?</strong></p><p>A module is loaded in three ways</p><ol><li>Eager loading</li><li>Lazy loading</li><li>Preloading</li></ol><p>Main module of application always loaded eagerly and feature module can be loaded in any ways.</p><p><strong>What is eager loading of modules?</strong></p><ul><li>In eager loading, all the feature modules are loaded at the start of the application, even if they are not immediately needed.</li><li>Eager loading is typically used when the developer expects all parts of the application to be used early on.</li></ul><p>Suppose we have a feature module as UserRoutingModule. To load it eagerly, just import it using @NgModule in main application module.</p><pre>@NgModule({<br>  imports: [<br>       ---------<br>       UserRoutingModule<br>  ],<br>})</pre><p>If more than one feature modules are configured, they will be loaded in the order they are configured in imports metadata.</p><p><strong>What is lazy loading of modules?</strong></p><ul><li>In lazy loading, all the feature modules are loaded on-demand.</li><li>They are not loaded at application start, they are loaded when there is a request to feature module.</li><li>It reduces the initial load time of the application and speeds up the startup process improving the performance.</li></ul><p>To load a module lazily, use loadChildren in route configuration as following.</p><pre>const routes: Routes = [<br>   {<br>        path: ‘user’,<br>        loadChildren: () =&gt; import(&#39;./user.module&#39;).then(mod =&gt; mod.UserModule)<br>   },<br>];</pre><p>Lazy loading is suitable for bigger application.</p><p><strong>What is preloading of modules?</strong></p><p>In preloading, feature modules are loaded asynchronously in background just after application start. For preloading, load module using loadChildren and configure preloadingStrategy with RouterModule.forRoot().</p><pre>const routes: Routes = [<br>   {<br>        path: ‘user’,<br>        loadChildren: () =&gt; import(&#39;./user.module&#39;).then(mod =&gt; mod.UserModule)<br>   }<br>]; <br><br>@NgModule({<br>  imports: [ RouterModule.forRoot(RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })) ],<br>  exports: [ RouterModule ]<br>})<br><br>export class AppRoutingModule{ }</pre><p>The <strong>PreloadAllModules</strong> strategy preloads all modules configured by <strong>loadChildren</strong>. To preload only selective modules, we need to create custom preloading strategy.</p><p><strong>How will you create custom preloading strategy?</strong></p><p>To create custom preloading strategy, create a class by overriding <strong>PreloadingStrategy</strong> abstract class that provides a preloading strategy. The built-in strategies are <strong>NoPreloading</strong> and <strong>PreloadAllModules</strong>.</p><pre>@Injectable()<br>export class CustomPreloadingStrategy implements PreloadingStrategy {<br>  preload(route: Route, load: () =&gt; Observable&lt;any&gt;): Observable&lt;any&gt; {<br>  }<br>}</pre><p>Now import CustomPreloadingStrategy in application module or feature module wherever required.</p><p><strong>How can you set the page title per route?</strong></p><p>The page title per route can be set using Route.title.</p><pre>{<br>  path: &#39;add&#39;,<br>  component: AddUserComponent,<br>  title: &#39;Add User’<br>}</pre><p>For the path /add, title will be <em>Add User</em>.</p><p><strong>How will you customize title using </strong><strong>TitleStrategy?</strong></p><p>The TitleStrategy is used to set the page title after a router navigation. It has three methods.</p><ul><li><strong>buildTitle()</strong> : Finds the existing title from RouterStateSnapshot.</li><li><strong>getResolvedTitleForRoute()</strong> : Returns the final value of Route.title property.</li><li><strong>updateTitle()</strong> : Updates the title.</li></ul><pre>@Injectable()<br>export class MyCustomTitleStrategy extends TitleStrategy {<br><br>  override updateTitle(routerState: RouterStateSnapshot) {<br>    const pageTitle = this.buildTitle(routerState);<br>    if (pageTitle !== undefined) {<br>      document.title = `ConcretePage - ${pageTitle}`;<br>    } else {<br>      document.title = `ConcretePage - Home`;<br>    }<br>  }<br><br>}</pre><p>Now configure the custom MyCustomTitleStrategy using provider in application module.</p><pre>providers: [ {provide: TitleStrategy,  useClass: MyCustomTitleStrategy} ] </pre><p><strong>What is </strong><strong>Route.providers?</strong></p><p>Route providers allows you to define dependencies that are available to that route and its child routes.</p><pre>{<br>  path: &#39;user&#39;,<br>  component: UserComponent,<br>  providers: [<br>       UserService<br>  ],<br>  children: [<br>  ]<br>}</pre><p>The UserService is available to the path <strong>/user</strong> and its children.</p><p><strong>How can you pass data to routed components?</strong></p><p>Using Route.data property in path configuration.</p><pre>import { Routes } from &#39;@angular/router&#39;;<br>import { MyRoutedComponent } from &#39;./my-routed/my-routed.component&#39;;<br><br>const routes: Routes = [<br>  {<br>    path: &#39;my-route&#39;,<br>    component: MyRoutedComponent,<br>    data: {<br>      pageTitle: &#39;My Custom Page&#39;,<br>      isAdmin: true<br>    }<br>  }<br>];<br><br>// ... rest of your routing module</pre><pre>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { ActivatedRoute } from &#39;@angular/router&#39;;<br><br>@Component({<br>  selector: &#39;app-my-routed&#39;,<br>  templateUrl: &#39;./my-routed.component.html&#39;,<br>  styleUrls: [&#39;./my-routed.component.css&#39;]<br>})<br><br>export class MyRoutedComponent implements OnInit {<br>  pageTitle: string;<br>  isAdmin: boolean;<br><br>  constructor(private route: ActivatedRoute) {}<br><br>  ngOnInit(): void {<br>    this.route.data.subscribe(data =&gt; {<br>      this.pageTitle = data[&#39;pageTitle&#39;];<br>      this.isAdmin = data[&#39;isAdmin&#39;];<br>    });<br>  }<br>}</pre><p><strong>What are Angular Guards?</strong></p><p>Angular Guards are used to control access to routes in an Angular application. They are used to protect routes from unauthorized access or to prevent unwanted navigation.</p><ul><li><strong>CanActivate: </strong>Determines if a route can be activated.</li><li><strong>CanActivateChild</strong>: Determines if a child route can be activated.</li><li><strong>CanDeactivate:</strong> Checks if a route can be deactivated. This is useful for prompting users to save unsaved changes before leaving a page.</li><li><strong>Resolve</strong>: Fetches data before a route is activated, ensures that data is available before the component is rendered.</li><li><strong>CanLoad:</strong> Determines if a module can be loaded lazily.</li><li><strong>CanMatch</strong>: Determines if a route’s path can be matched and activated.</li></ul><pre>const routes: Routes = [<br><br>  { <br>    path: &#39;users&#39;, <br>    component: UsersComponent, <br>    children: [<br>      { path: &#39;:id&#39;, component: UserDetailsComponent },<br>      { path: &#39;&#39;, component: PlaceholderComponent }<br>    ],<br>    canActivate: [CanActivateGuard],<br>    canActivateChild: [CanActivateChildGuard],<br>  },<br><br>  { <br>    path: &#39;home&#39;, <br>    component: HomeComponent <br>  },<br><br>  { <br>    path: &#39;form&#39;, <br>    component: FormComponent, <br>    canDeactivate: [CanDeactivateGuard] <br>  },<br><br>  { <br>    path: &#39;dashboard&#39;,<br>    loadChildren: () =&gt; import(&#39;./dashboard/dashboard.module&#39;).then(m =&gt; m.DashboardModule), <br>    canLoad: [CanLoadGuard] <br>  },<br><br>  { path: &#39;**&#39;, redirectTo: &#39;/home&#39; },<br><br>];<br><br>@NgModule({<br>  imports: [RouterModule.forRoot(routes)],<br>  exports: [RouterModule],<br>  providers: [CanActivateGuard, CanActivateChildGuard, CanDeactivateGuard, CanLoadGuard]<br>})</pre><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from &#39;@angular/router&#39;;<br>import { Observable } from &#39;rxjs&#39;;<br>import { take } from &#39;rxjs/operators&#39;;<br>import { AuthService } from &#39;./auth.service&#39;;<br><br>@Injectable()<br>export class CanActivateGuard implements CanActivate {<br><br>  constructor(private readonly authService: AuthService) {}<br><br>  canActivate(<br>    next: ActivatedRouteSnapshot,<br>    state: RouterStateSnapshot): Observable&lt;boolean&gt; | Promise&lt;boolean&gt; | boolean {<br>    return this.authService.isAuthenticated$;<br>  }<br>}</pre><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { CanActivateChild, ActivatedRouteSnapshot, RouterStateSnapshot } from &#39;@angular/router&#39;;<br>import { Observable } from &#39;rxjs&#39;;<br>import { AuthService } from &#39;./auth.service&#39;;<br><br>@Injectable()<br>export class CanActivateChildGuard implements CanActivateChild {<br><br>  constructor(private readonly authService: AuthService) {}<br><br>  canActivateChild(<br>    next: ActivatedRouteSnapshot,<br>    state: RouterStateSnapshot): Observable&lt;boolean&gt; | Promise&lt;boolean&gt; | boolean {<br>    return this.authService.isAuthenticated$;<br>  }<br>}</pre><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from &#39;@angular/router&#39;;<br>import { Observable } from &#39;rxjs&#39;;<br><br>export interface CanComponentDeactivate {<br>  confirm(): boolean;<br>}<br><br>@Injectable()<br>export class CanDeactivateGuard implements CanDeactivate&lt;CanComponentDeactivate&gt; {<br><br>  canDeactivate(<br>    component: CanComponentDeactivate, <br>    currentRoute: ActivatedRouteSnapshot, <br>    currentState: RouterStateSnapshot, <br>    nextState?: RouterStateSnapshot): Observable&lt;boolean | UrlTree&gt; | Promise&lt;boolean | UrlTree&gt; | boolean | UrlTree {<br>    return component.confirm();<br>  }<br>}</pre><pre>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { CanComponentDeactivate } from &#39;../can-deactivate.guard&#39;;<br><br>@Component({<br>  selector: &#39;app-form&#39;,<br>  templateUrl: &#39;./form.component.html&#39;,<br>  styleUrls: [&#39;./form.component.css&#39;]<br>})<br><br>export class FormComponent implements OnInit, CanComponentDeactivate {<br><br>  constructor() { }<br><br>  ngOnInit() {<br>  }<br><br>  confirm() {<br>    return confirm(&#39;Are you sure you want to abandon the unsaved changes?&#39;);<br>  }<br>}</pre><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { CanLoad, Route, UrlSegment, Router } from &#39;@angular/router&#39;;<br>import { Observable } from &#39;rxjs&#39;;<br>import { take } from &#39;rxjs/operators&#39;;<br>import { AuthService } from &#39;./auth.service&#39;;<br><br>@Injectable()<br>export class CanLoadGuard implements CanLoad {<br><br>  constructor(private readonly authService: AuthService) {}<br><br>  canLoad(<br>    route: Route,<br>    segments: UrlSegment[]<br>  ): Observable&lt;boolean&gt; | Promise&lt;boolean&gt; | boolean {<br>    return this.authService.isAuthenticated$.pipe(take(1));<br>  }<br>}</pre><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { CommonModule } from &#39;@angular/common&#39;;<br>import { DashboardComponent } from &#39;./dashboard/dashboard.component&#39;;<br>import { DashboardRoutingModule } from &#39;./dashboard-routing.module&#39;;<br><br>@NgModule({<br>  imports: [<br>    DashboardRoutingModule,<br>    CommonModule<br>  ],<br>  declarations: [DashboardComponent]<br>})<br><br>export class DashboardModule { }</pre><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { RouterModule, Routes } from &#39;@angular/router&#39;;<br>import { DashboardComponent } from &#39;./dashboard/dashboard.component&#39;;<br><br>const routes: Routes = [<br>  { path: &#39;&#39;, component: DashboardComponent },<br>];<br><br>@NgModule({<br>  imports: [RouterModule.forChild(routes)],<br>  exports: [RouterModule]<br>})<br><br>export class DashboardRoutingModule { }</pre><p><a href="https://stackblitz.com/edit/angular-guards-8973847">https://stackblitz.com/edit/angular-guards-8973847</a></p><p><strong>What is a Resolver in Angular?</strong></p><ul><li>Fetches data before a route is activated, ensures that data is available before the component is rendered.</li><li>Ensures that the necessary data is available when the route is accessed.</li></ul><p>Useful for loading important data that a component depends on, thereby enhancing user experience by avoiding loading indicators or incomplete views.</p><p><strong>1. Create a Data Service:</strong></p><pre>// data.service.ts<br>import { Injectable } from &#39;@angular/core&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;<br>import { Observable } from &#39;rxjs&#39;;<br><br>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br><br>export class DataService {<br>  private apiUrl = &#39;https://jsonplaceholder.typicode.com/posts&#39;; // Example API<br><br>  constructor(private http: HttpClient) {}<br><br>  getPosts(): Observable&lt;any&gt; {<br>    return this.http.get(this.apiUrl);<br>  }<br><br>  getPostById(id: number): Observable&lt;any&gt; {<br>    let params = new HttpParams();<br>    params = params.set(&#39;id&#39;, id.toString());<br>    return this.http.get(this.apiUrl, { params });<br>  }<br>}</pre><p><strong>2. Create a Resolver:</strong></p><pre>// post.resolver.ts<br>import { inject } from &#39;@angular/core&#39;;<br>import { ResolveFn, ActivatedRouteSnapshot } from &#39;@angular/router&#39;;<br>import { DataService } from &#39;./data.service&#39;;<br>import { Observable } from &#39;rxjs&#39;;<br><br>export const postResolver: ResolveFn&lt;any&gt; = (route: ActivatedRouteSnapshot): Observable&lt;Post&gt; =&gt; {<br>  const dataService = inject(DataService);<br>  const postId = route.paramMap.get(&#39;id&#39;);<br><br>  if (postId) {<br>    return dataService.getPostById(+postId);<br>  }<br><br>  // Handle cases where ID is missing or return a default/error value<br>  throw new Error(&#39;Post ID not found in route parameters.&#39;);<br>};</pre><p><strong>3. Configure the Route:</strong></p><pre>// app-routing.module.ts<br>import { NgModule } from &#39;@angular/core&#39;;<br>import { RouterModule, Routes } from &#39;@angular/router&#39;;<br>import { PostDetailComponent } from &#39;./post-detail/post-detail.component&#39;;<br>import { postResolver } from &#39;./post.resolver&#39;;<br><br>const routes: Routes = [<br>  {<br>    path: &#39;posts/:id&#39;,<br>    component: PostDetailComponent,<br>    resolve: {<br>      postData: postResolver // &#39;postData&#39; is the key to access the resolved data<br>    }<br>  },<br>  // ... other routes<br>];<br><br>@NgModule({<br>  imports: [RouterModule.forRoot(routes)],<br>  exports: [RouterModule]<br>})<br><br>export class AppRoutingModule { }</pre><p><strong>4. Access Resolved Data in the Component:</strong></p><pre>// post-detail.component.ts<br>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { ActivatedRoute } from &#39;@angular/router&#39;;<br><br>@Component({<br>  selector: &#39;app-post-detail&#39;,<br>  templateUrl: &#39;./post-detail.component.html&#39;,<br>  styleUrls: [&#39;./post-detail.component.css&#39;]<br>})<br><br>export class PostDetailComponent implements OnInit {<br>  post;<br><br>  constructor(private route: ActivatedRoute) {}<br><br>  ngOnInit(): void {<br>    this.route.data.subscribe(data =&gt; {<br>      this.post = data[&#39;postData&#39;]; // Access using the key defined in the route<br>    });<br>  }<br>}</pre><p><strong>Read More:</strong></p><ul><li><a href="https://dhilip-me.medium.com/angular-interview-preparation-db274264c3a1"><strong>Angular_Basics_Overview</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-lifecycle-hooks-mvvm-architecture-a6cca524ac09"><strong>Angular_Lifecycle_Hooks_And_MVVM_Architecture</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-synchronous-and-asynchronous-behaviors-3e1538f067b2"><strong>Angular_Synchronous_and_Asynchronous_Behaviors</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-pipes-6ccd97de6af1"><strong>Angular_Pipes</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/97941c37d897"><strong>Angular_Forms</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-router-586a84463179"><strong>Angular_Routing</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/angular-interceptors-1c918da59884"><strong>Angular_Interceptors</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-web-workers-1a41d79783d3"><strong>Angular_Web_Workers</strong></a></li><li><a href="https://dhilip-me.medium.com/rxjs-in-angular-63ae9902c4b7"><strong>RxJS_in_Angular</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/69d1fbf8a9fc"><strong>Operators_in_RxJS</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-application-optimization-1f59c0074c42"><strong>Angular_Application_Optimization</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/angular-scenario-based-interview-questions-991e8744fcac"><strong>Angular_Scenario_Based_Interview_Question</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=586a84463179" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Operators in RxJS]]></title>
            <link>https://dhilip-me.medium.com/operators-in-rxjs-69d1fbf8a9fc?source=rss-bc6e6d0c9eb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/69d1fbf8a9fc</guid>
            <category><![CDATA[rxjs-operators]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Dhilip Kumar]]></dc:creator>
            <pubDate>Mon, 01 Dec 2025 07:53:15 GMT</pubDate>
            <atom:updated>2025-12-12T09:05:48.478Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What are some commonly used operators in RxJS?</strong></p><p>Operators are grouped into the following sections:</p><ul><li><strong>Creation Operators</strong> (e.g., of, from, ajax, interval, timer)</li><li><strong>Transformation Operators</strong> (e.g., map, mergeMap, concatMap, switchMap, exhaustMap)</li><li><strong>Filtering Operators</strong> (e.g., filter, take, takeUntil, debounceTime, distinctUntilChanged)</li><li><strong>Combination Operators</strong> (e.g., concat, merge, combineLatest, forkJoin, zip, withLatestFrom)</li><li><strong>Utility Operators</strong> (e.g., tap, delay, finalize)</li><li><strong>Error Handling Operators</strong> (e.g., catchError, retry, retryWhen)</li><li><strong>Multicasting Operators</strong> (e.g., share, shareReplay)</li></ul><p><strong>of: </strong>Used to convert one or more static values into an Observable sequence. It emits all the provided arguments in sequence, immediately on subscription, and then sends a complete notification.</p><pre>import { of } from &#39;rxjs&#39;;<br><br>// Emitting a sequence of numbers<br>const numbers$ = of(1, 2, 3, 4, 5);<br>numbers$.subscribe(<br>  (value) =&gt; console.log(&#39;Number:&#39;, value),<br>  (error) =&gt; console.error(&#39;Error:&#39;, error),<br>  () =&gt; console.log(&#39;Numbers completed&#39;)<br>);<br><br>// Output:<br>// Number: 1<br>// Number: 2<br>// Number: 3<br>// Number: 4<br>// Number: 5<br>// Numbers completed<br><br>// Emitting different types of values<br>const mixedData$ = of({ name: &#39;Alice&#39; }, [10, 20], &#39;hello&#39;);<br>mixedData$.subscribe(<br>  (value) =&gt; console.log(&#39;Data:&#39;, value),<br>  (error) =&gt; console.error(&#39;Error:&#39;, error),<br>  () =&gt; console.log(&#39;Mixed data completed&#39;)<br>);<br><br>// Output:<br>// Data: { name: &#39;Alice&#39; }<br>// Data: [10, 20]<br>// Data: hello<br>// Mixed data completed</pre><p><strong>from: </strong>Converts an array, promise, or iterable into an observable.</p><pre>import { from } from &#39;rxjs&#39;;<br><br>const myArray = [1, 2, 3];<br>from(myArray).subscribe(val =&gt; console.log(val));<br><br>// Output:<br>// 1<br>// 2<br>// 3<br><br>const myString = &#39;Hello&#39;;<br>from(myString).subscribe(char =&gt; console.log(char));<br><br>// Output:<br>// H<br>// e<br>// l<br>// l<br>// o</pre><p><strong>ajax: </strong>Performs an XMLHttpRequest with the provided options and returns an observable.</p><pre>import { ajax } from &#39;rxjs/ajax&#39;;<br><br>// Making a GET request to a URL<br>ajax.getJSON(&#39;https://api.example.com/data&#39;)<br>  .subscribe(<br>    data =&gt; console.log(&#39;Data received:&#39;, data),<br>    error =&gt; console.error(&#39;Error:&#39;, error)<br>);</pre><p><strong>interval: </strong>Creates an observable that emits a sequence of numbers at a specified time interval starting from 0.</p><pre>import { interval, take } from &#39;rxjs&#39;;<br><br>// Create an Observable that emits a value every 1000 milliseconds (1 second)<br>const numbers = interval(1000);<br><br>// Subscribe to the Observable to receive the emitted values<br>numbers.pipe(take(5)).subscribe(x =&gt; console.log(&#39;Next: &#39;, x));<br><br>// Expected output:<br>// Next: 0<br>// Next: 1<br>// Next: 2<br>// Next: 3<br>// Next: 4</pre><p><strong>timer: </strong>Creates an observable that emits a value after a specified delay, similar to setTimeout.</p><pre>import { timer } from &#39;rxjs&#39;;<br><br>const source = timer(2000); // Emit 0 after 2000 milliseconds (2 seconds)<br><br>source.subscribe(<br>  val =&gt; console.log(&#39;Emitted:&#39;, val),<br>  err =&gt; console.error(&#39;Error:&#39;, err),<br>  () =&gt; console.log(&#39;Timer completed.&#39;)<br>);</pre><pre>Emitted:0<br>Timer completed.</pre><pre>import { timer } from &#39;rxjs&#39;;<br>    <br>const source = timer(1000, 2000); // Emit first value after 1s, then every 2s<br><br>source<br>.pipe(take(3))<br>.subscribe(<br>  (val) =&gt; console.log(&#39;Emitted:&#39;, val),<br>  (err) =&gt; console.error(&#39;Error:&#39;, err),<br>  () =&gt; console.log(&#39;Timer completed.&#39;)<br>);</pre><pre>Emitted:0<br>Emitted:1<br>Emitted:2<br>Timer completed.</pre><p><strong>map: </strong>It is a flattening operator used to transform emitted data in desired format.</p><pre>import { Observable } from &#39;rxjs&#39;;<br>import { map, filter } from &#39;rxjs/operators&#39;;<br><br>const numbers = Observable.of(1, 2, 3, 4, 5);<br>numbers.pipe(<br>  map(num =&gt; num * 2),<br>  filter(num =&gt; num &gt; 5)<br>).subscribe(result =&gt; console.log(result)); <br><br>// Output: 6, 8, 10</pre><p><strong>mergeMap (flatMap):</strong></p><ul><li>Maps each value to an Observable and then merges all the resulting Observables, emitting values concurrently as they arrive without waiting for the previous one to finish.</li><li>Ideal for tasks like handling multiple API calls at once where the order of results doesn’t matter.</li></ul><pre>import { Component } from &#39;@angular/core&#39;;<br>import { Subject, Subscription, timer } from &#39;rxjs&#39;;<br>import { concatMap, mapTo, mergeMap, tap } from &#39;rxjs/operators&#39;;<br><br>@Component({<br>  selector: &#39;my-app&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.css&#39;],<br>})<br><br>export class AppComponent {<br>  sub = new Subject&lt;string&gt;();<br>  private subscription: Subscription;<br><br>  ngOnInit() {<br>    this.subscription = this.sub<br>      .asObservable()<br>      .pipe(<br>        tap((value) =&gt; console.log(&#39;--&gt; sent out&#39;, value)),<br>        mergeMap((value) =&gt; this.anyLongRunningOp(value))<br>      )<br>      .subscribe((value) =&gt; console.log(&#39;&lt;-- received&#39;, value));<br><br>    this.sub.next(&#39;first&#39;);<br>    this.sub.next(&#39;second&#39;);<br>  }<br><br>  anyLongRunningOp(value: string) {<br>    return timer(2000).pipe(mapTo(value));<br>  }<br>}</pre><pre>--&gt; sent out first<br>--&gt; sent out second<br>&lt;-- received first<br>&lt;-- received second</pre><p><strong>concatMap:</strong></p><ul><li>Maps each value to an Observable and then concatenates the resulting Observables, emitting values in order waits for the previous one to complete before starting the next.</li></ul><pre>import { Component } from &#39;@angular/core&#39;;<br>import { Subject, Subscription, timer } from &#39;rxjs&#39;;<br>import { concatMap, mapTo, mergeMap, tap } from &#39;rxjs/operators&#39;;<br><br>@Component({<br>  selector: &#39;my-app&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.css&#39;],<br>})<br><br>export class AppComponent {<br>  sub = new Subject&lt;string&gt;();<br>  private subscription: Subscription;<br><br>  ngOnInit() {<br>    this.subscription = this.sub<br>      .asObservable()<br>      .pipe(<br>        tap((value) =&gt; console.log(&#39;--&gt; sent out&#39;, value)),<br>        concatMap((value) =&gt; this.anyLongRunningOp(value))<br>      )<br>      .subscribe((value) =&gt; console.log(&#39;&lt;-- received&#39;, value));<br><br>    this.sub.next(&#39;first&#39;);<br>    this.sub.next(&#39;second&#39;);<br>  }<br><br>  anyLongRunningOp(value: string) {<br>    return timer(2000).pipe(mapTo(value));<br>  }<br>}</pre><pre>--&gt; sent out first<br>--&gt; sent out second<br>&lt;-- received first<br>&lt;-- received second</pre><p><strong>switchMap:</strong></p><ul><li>Maps each value to an Observable, then flattens all the inner Observables, emitting values only from the most recent Observable.</li><li>It cancels any previous inner observable when the source emits a new value. It’s used to handle scenarios where you only care about the latest data and want to ignore responses from previous requests.</li></ul><pre>import { Component } from &#39;@angular/core&#39;;<br>import { Subject, Subscription, timer } from &#39;rxjs&#39;;<br>import { concatMap, mapTo, mergeMap, switchMap, tap } from &#39;rxjs/operators&#39;;<br><br>@Component({<br>  selector: &#39;my-app&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.css&#39;],<br>})<br><br>export class AppComponent {<br>  sub = new Subject&lt;string&gt;();<br>  private subscription: Subscription;<br><br>  ngOnInit() {<br>    this.subscription = this.sub<br>      .asObservable()<br>      .pipe(<br>        tap((value) =&gt; console.log(&#39;--&gt; sent out&#39;, value)),<br>        switchMap((value) =&gt; this.anyLongRunningOp(value))<br>      )<br>      .subscribe((value) =&gt; console.log(&#39;&lt;-- received&#39;, value));<br><br>    this.sub.next(&#39;first&#39;);<br>    this.sub.next(&#39;second&#39;);<br>  }<br><br>  anyLongRunningOp(value: string) {<br>    return timer(2000).pipe(mapTo(value));<br>  }<br>}</pre><pre>--&gt; sent out first<br>--&gt; sent out second<br>&lt;-- received second</pre><p><strong>exhaustMap:</strong></p><ul><li>It is used to handle events where only one ongoing operation should be active at a time, and subsequent events should be ignored until the current operation completes.</li><li>Useful for scenarios like preventing multiple API calls from being triggered by rapid button clicks or form submissions.</li></ul><pre>import { Component } from &#39;@angular/core&#39;;<br>import { Subject, Subscription, timer } from &#39;rxjs&#39;;<br>import { concatMap, exhaustMap, mapTo, mergeMap, switchMap, tap } from &#39;rxjs/operators&#39;;<br><br>@Component({<br>  selector: &#39;my-app&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.css&#39;],<br>})<br><br>export class AppComponent {<br>  sub = new Subject&lt;string&gt;();<br>  private subscription: Subscription;<br><br>  ngOnInit() {<br>    this.subscription = this.sub<br>      .asObservable()<br>      .pipe(<br>        tap((value) =&gt; console.log(&#39;--&gt; sent out&#39;, value)),<br>        exhaustMap((value) =&gt; this.anyLongRunningOp(value))<br>      )<br>      .subscribe((value) =&gt; console.log(&#39;&lt;-- received&#39;, value));<br><br>    this.sub.next(&#39;first&#39;);<br>    this.sub.next(&#39;second&#39;);<br>  }<br><br>  anyLongRunningOp(value: string) {<br>    return timer(2000).pipe(mapTo(value));<br>  }<br>}</pre><pre>--&gt; sent out first<br>--&gt; sent out second<br>&lt;-- received first</pre><p><strong>filter: </strong>filter operator emits items from a source Observable that satisfy a predicate</p><pre>import { Observable } from &#39;rxjs&#39;;<br>import { map, filter } from &#39;rxjs/operators&#39;;<br><br>const numbers = Observable.of(1, 2, 3, 4, 5);<br>numbers.pipe(<br>  map(num =&gt; num * 2),<br>  filter(num =&gt; num &gt; 5)<br>).subscribe(result =&gt; console.log(result)); <br><br>// Output: 6, 8, 10</pre><p><strong>take:</strong></p><ul><li>take operator limits the number of emissions from an observable. It emits the initial n values from the source observable and then automatically completes the stream and unsubscribes</li></ul><pre>import { timer } from &#39;rxjs&#39;;<br>import { take } from &#39;rxjs/operators&#39;;<br><br>// Create an observable that emits a value every 1000ms, starting immediately<br>const source$ = timer(0, 1000);<br><br>// Take the first 3 emissions from the source$<br>source$.pipe(<br>  take(3)<br>).subscribe({<br>  next: value =&gt; console.log(`Received: ${value}`),<br>  complete: () =&gt; console.log(&#39;Observable completed!&#39;)<br>});</pre><pre>Received: 0<br>Received: 1<br>Received: 2<br>Observable completed!</pre><p><strong>takeUntil:</strong></p><ul><li>It is a filtering operator that completes an observable when another observable (“notifier”) emits a value.</li><li>Used for managing subscriptions to prevent memory leaks by automatically unsubscribing from observables, for example, when a component is destroyed.</li></ul><pre>import { interval, Subject } from &#39;rxjs&#39;;<br>import { takeUntil } from &#39;rxjs/operators&#39;;<br><br>const source$ = interval(1000); // Emits 0, 1, 2, ... every second<br>const stop$ = new Subject(); // Our notifier<br><br>source$.pipe(<br>  takeUntil(stop$) // Stop when stop$.next() is called<br>).subscribe(value =&gt; console.log(value));<br><br>// After 3 seconds, call stop$.next() to cancel the subscription<br>setTimeout(() =&gt; {<br>  stop$.next();<br>  stop$.complete(); // Good practice to complete the subject too<br>  console.log(&quot;Subscription stopped!&quot;);<br>}, 3000);<br><br>// Output: 0, 1, 2 (then stops)</pre><p><strong>debounceTime:</strong></p><ul><li>Emits value from the source observable only after a specified duration has passed without any other value being emitted.</li><li>Used in scenarios involving rapid, continuous events like user input.</li></ul><pre>&lt;input type=&quot;text&quot; [formControl]=&quot;searchControl&quot; placeholder=&quot;Search...&quot;&gt;<br>&lt;p&gt;Search Term: {{ searchTerm }}&lt;/p&gt;</pre><pre>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { FormControl } from &#39;@angular/forms&#39;;<br>import { debounceTime, distinctUntilChanged } from &#39;rxjs/operators&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.css&#39;]<br>})<br><br>export class AppComponent implements OnInit {<br>  searchControl = new FormControl(&#39;&#39;);<br>  searchTerm: string = &#39;&#39;;<br><br>  ngOnInit() {<br>    this.searchControl.valueChanges<br>      .pipe(<br>        debounceTime(500), // Wait for 500ms of inactivity<br>        distinctUntilChanged() // Only emit if the value has changed<br>      )<br>      .subscribe(value =&gt; {<br>        this.searchTerm = value;<br>        // Here you would typically trigger an action, e.g., an API call<br>        console.log(&#39;Debounced search term:&#39;, value);<br>      });<br>  }<br>}</pre><pre>Debounced search term:<br>h<br>Debounced search term:<br>he<br>Debounced search term:<br>hello</pre><p><strong>distinctUntilChanged:</strong></p><p>Emits a value only if it is different from the previous value.</p><pre>import { of, distinctUntilChanged } from &#39;rxjs&#39;;<br><br>const source$ = of(1, 1, 2, 2, 1, 1, 3);<br>source$.pipe(distinctUntilChanged()).subscribe(console.log);<br>// Output: 1, 2, 1, 3</pre><pre>import { of, distinctUntilChanged } from &#39;rxjs&#39;;<br><br>const source$ = of(<br>  { id: &#39;1&#39;, name: &#39;John&#39; },<br>  { id: &#39;2&#39;, name: &#39;John&#39; }, // will be filtered out<br>  { id: &#39;3&#39;, name: &#39;Jane&#39; }<br>);<br><br>const customCompare = (a, b) =&gt; a.name === b.name;<br><br>source$.pipe(distinctUntilChanged(customCompare)).subscribe(console.log);<br>// Output: { id: &#39;1&#39;, name: &#39;John&#39; }, { id: &#39;3&#39;, name: &#39;Jane&#39; }</pre><p><strong>concat: </strong>Combines multiple Observables into a single Observable, emitting values sequentially, one after the other. It ensures that the Observables are processed in the order they are provided.</p><pre>import { concat, of } from &#39;rxjs&#39;;<br>import { delay } from &#39;rxjs/operators&#39;;<br><br>const observable1 = of(1, 2, 3).pipe(delay(1000)); // Emits after 1 second<br>const observable2 = of(&#39;A&#39;, &#39;B&#39;, &#39;C&#39;).pipe(delay(500)); // Emits after 0.5 seconds<br><br>const result = concat(observable1, observable2);<br>result.subscribe(value =&gt; console.log(value));<br><br>// Expected output:<br>// 1 (after 1 second)<br>// 2 (after 1 second)<br>// 3 (after 1 second)<br>// A (after 1.5 seconds total)<br>// B (after 1.5 seconds total)<br>// C (after 1.5 seconds total)</pre><p><strong>merge:</strong> Combines multiple observables into a single one, emitting values concurrently as they arrive from any source observable.</p><pre>const interval1$ = interval(1000);<br>const interval2$ = interval1$.pipe(map(val =&gt; 10 * val));<br><br>// The order matters which value you receive first<br>const result$ = merge(interval2$, interval1$).pipe(<br>  take(8) // Get first 8 values<br>).subscribe(console.log);</pre><pre>0<br>0<br>10<br>1<br>20<br>2<br>30<br>3</pre><p><strong>combineLatest: </strong>Combines the latest values from multiple observables into an array or object.</p><pre>// app.component.ts<br>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { Observable, combineLatest, of } from &#39;rxjs&#39;;<br><br>@Component({<br>    selector: &#39;app-root&#39;,<br>    templateUrl: &#39;./app.component.html&#39;,<br>    styleUrls: [&#39;./app.component.css&#39;],<br>})<br><br>export class AppComponent implements OnInit {<br>    combinedValues: [number, string][] = [];<br><br>    ngOnInit() {<br>        const observable1: Observable&lt;number&gt; = of(1, 2);<br>        const observable2: Observable&lt;string&gt; = of(&#39;A&#39;, &#39;B&#39;);<br>        const combinedObservable: Observable&lt;[number, string]&gt; = combineLatest(<br>            observable1,<br>            observable2<br>        );<br>        combinedObservable.subscribe((pair) =&gt; {<br>            this.combinedValues.push(pair);<br>        });<br>        console.log(combinedValues);<br>        //[[2, A], [2, B]]<br>    }<br>}</pre><p><strong>forkJoin</strong>: Combines multiple Observables into a single Observable, emits an array of values, only once all the input Observables have completed.</p><pre>import { forkJoin } from &#39;rxjs&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;<br><br>constructor(private http: HttpClient) { }<br><br>getData() {<br>    const api1$ = this.http.get(&#39;https://api1.example.com&#39;);<br>    const api2$ = this.http.get(&#39;https://api2.example.com&#39;);<br>    forkJoin([api1$, api2$]).subscribe(<br>        ([api1Response, api2Response]) =&gt; {<br>            // Process data from both APIs<br>            this.processData(api1Response, api2Response);<br>        },<br>        error =&gt; {<br>            console.error(&#39;Error fetching data&#39;, error);<br>        }<br>    );<br>}</pre><p><strong>zip:</strong></p><ul><li>Combines the emissions of multiple Observables together.</li><li>It works by taking the corresponding values from each input Observable and emitting them as a single array, but only after all input Observables have emitted at least one value.</li></ul><pre>import { Component } from &#39;@angular/core&#39;;<br>import { zip, of } from &#39;rxjs&#39;;<br>import { delay } from &#39;rxjs/operators&#39;;<br><br>@Component({<br>  selector: &#39;app-zip-example&#39;,<br>  template: `<br>    &lt;p&gt;Zipped values: {{ zippedValues | json }}&lt;/p&gt;<br>  `,<br>})<br><br>export class ZipExampleComponent {<br>  zippedValues: any;<br><br>  constructor() {<br>    const observable1 = of(1, 2, 3).pipe(delay(1000)); // Emits after 1 second<br>    const observable2 = of(&#39;A&#39;, &#39;B&#39;, &#39;C&#39;).pipe(delay(500));  // Emits after 0.5 seconds<br>    <br>    zip(observable1, observable2).subscribe(<br>      ([value1, value2]) =&gt; {<br>        this.zippedValues = { value1, value2 };<br>        console.log(`Combined: ${value1}, ${value2}`);<br>      },<br>      (error) =&gt; console.error(&#39;Error:&#39;, error),<br>      () =&gt; console.log(&#39;Zip completed&#39;)<br>    );<br>  }<br>}</pre><pre>Combined: 1, A<br>Combined: 2, B<br>Combined: 3, C<br>Zip completed</pre><p><strong>withLatestFrom:</strong></p><ul><li>Combines latest value from a source observable with the latest values from one or more other observables, but <strong>only when the source observable emits</strong>.</li><li>Both observables must have emitted at least one value.</li><li>The result is an array containing the value from the source and the latest value from the other observable(s).</li></ul><pre>import { interval } from &#39;rxjs&#39;;<br>import { withLatestFrom, map } from &#39;rxjs/operators&#39;;<br><br>// Source observable: emits a value every 5 seconds<br>const source = interval(5000);<br><br>// Other observable: emits a value every 1 second<br>const secondSource = interval(1000);<br><br>const example = source.pipe(<br>  take(3),<br>  // When &#39;source&#39; emits, combine its value with the latest value from &#39;secondSource&#39;<br>  withLatestFrom(secondSource),<br>  // Map the combined values into a readable string<br>  map(([first, second]) =&gt; {<br>    return `First Source (5s): ${first}, Second Source (1s): ${second}`;<br>  })<br>);<br><br>// Subscribe to the example observable to see the output<br>const subscribe = example.subscribe(val =&gt; console.log(val));</pre><pre>First Source (5s): 0, Second Source (1s): 4<br>First Source (5s): 1, Second Source (1s): 9<br>First Source (5s): 2, Second Source (1s): 14</pre><p><strong>tap:</strong></p><ul><li>Performs side effects for each emission on the source observable without modifying the emitted values.</li><li>Used for logging, debugging, or other non-transformative actions.</li></ul><pre>import { of } from &#39;rxjs&#39;;<br>import { tap, map } from &#39;rxjs/operators&#39;;<br><br>const source = of(1, 2, 3);<br>source.pipe(<br>  tap(value =&gt; console.log(&#39;Value before map:&#39;, value)), // Log the value before transformation<br>  map(value =&gt; value * 2), // Transform the value<br>  tap(value =&gt; console.log(&#39;Value after map:&#39;, value)) // Log the value after transformation<br>).subscribe(<br>  finalValue =&gt; console.log(&#39;Subscribed value:&#39;, finalValue),<br>  error =&gt; console.error(&#39;Error:&#39;, error),<br>  () =&gt; console.log(&#39;Completed&#39;)<br>);</pre><pre>Value before map: 1<br>Value after map: 2<br>Subscribed value: 2<br>Value before map: 2<br>Value after map: 4<br>Subscribed value: 4<br>Value before map: 3<br>Value after map: 6<br>Subscribed value: 6<br>Completed</pre><p><strong>delay: </strong>Delays emissions of an Observable by a specified timeout in milliseconds or until a given Date.</p><pre>import { of } from &#39;rxjs&#39;;<br>import { delay } from &#39;rxjs/operators&#39;;<br><br>const source = of(1, 2, 3);<br><br>source.pipe(delay(1000)).subscribe(value =&gt; {<br>  console.log(`Received value after 1 second: ${value}`);<br>});<br><br>// Output:<br>// (after 1 second) Received value after 1 second: 1<br>// (shortly after) Received value after 1 second: 2<br>// (shortly after) Received value after 1 second: 3</pre><pre>import { fromEvent } from &#39;rxjs&#39;;<br>import { delay } from &#39;rxjs/operators&#39;;<br><br>const clicks = fromEvent(document, &#39;click&#39;);<br>const futureDate = new Date(&#39;December 31, 2050 12:00:00&#39;); <br><br>clicks.pipe(delay(futureDate)).subscribe(event =&gt; {<br>  console.log(&#39;Click event received after the future date:&#39;, event);<br>});<br><br>// No click events will be logged until December 31, 2050 at 12:00:00</pre><p><strong>finalize: </strong>Executes a callback function when the source Observable completes, errors, or when the subscriber unsubscribes.</p><pre>import { of } from &#39;rxjs&#39;;<br>import { finalize } from &#39;rxjs/operators&#39;;<br><br>console.log(&#39;Observable stream initiated.&#39;);<br><br>of(1, 2, 3)<br>  .pipe(<br>    finalize(() =&gt; {<br>      console.log(&#39;Finalize callback executed: Stream terminated.&#39;);<br>      // This is where cleanup logic or side effects would go<br>    })<br>  )<br>  .subscribe({<br>    next: value =&gt; console.log(`Emitted value: ${value}`),<br>    error: err =&gt; console.error(`Error: ${err}`),<br>    complete: () =&gt; console.log(&#39;Observable completed.&#39;)<br>  });<br><br>console.log(&#39;Observable stream setup complete.&#39;);</pre><pre>Observable stream initiated.<br>Emitted value: 1<br>Emitted value: 2<br>Emitted value: 3<br>Observable completed.<br>Finalize callback executed: Stream terminated.<br>Observable stream setup complete.</pre><p><strong>catchError: </strong>Used to handle errors within the Observable pipeline.</p><pre>import { of, throwError } from &#39;rxjs&#39;;<br>import { catchError, map } from &#39;rxjs/operators&#39;;<br><br>// An observable that might throw an error<br>const sourceObservable = of(1, 2, 3, 4).pipe(<br>  map(value =&gt; {<br>    if (value === 3) {<br>      throw new Error(&#39;Value 3 encountered, causing an error!&#39;);<br>    }<br>    return value;<br>  })<br>);<br><br>sourceObservable.pipe(<br>  catchError(error =&gt; {<br>    console.error(&#39;Caught error:&#39;, error.message);<br>    // Return a new observable as a fallback<br>    return of(&#39;Fallback value&#39;);<br>    // Or rethrow the error for higher-level handling:<br>    // return throwError(() =&gt; new Error(&#39;Custom error after catching: &#39; + error.message));<br>  })<br>).subscribe({<br>  next: value =&gt; console.log(&#39;Received:&#39;, value),<br>  error: err =&gt; console.error(&#39;Subscription error:&#39;, err.message),<br>  complete: () =&gt; console.log(&#39;Completed!&#39;)<br>});</pre><pre>Received:1<br>Received:2<br>Caught error:Value 3 encountered, causing an error!<br>Received:Fallback value<br>Completed!</pre><p><strong>retry: </strong>Resubscribes to the source observable specified number of times if an error occurs.</p><pre>import { interval } from &#39;rxjs&#39;;<br>import { map, retry } from &#39;rxjs/operators&#39;;<br><br>const source = interval(1000);<br><br>const example = source.pipe(<br>  map(val =&gt; {<br>    if (val &gt; 2) {<br>      throw new Error(&#39;Value too high!&#39;);<br>    }<br>    return val;<br>  }),<br>  retry(2) // Retries 2 times before throwing the error<br>);<br><br>example.subscribe(<br>  val =&gt; console.log(val),<br>  err =&gt; console.error(err.message),<br>  () =&gt; console.log(&#39;Complete&#39;)<br>);<br><br>/*<br>Output:<br>0<br>1<br>2<br>0<br>1<br>2<br>0<br>1<br>2<br>Value too high!<br>*/</pre><p><strong>retryWhen: </strong>Provides error handling mechanism with custom retry logic.</p><pre>import { interval, timer } from &#39;rxjs&#39;;<br>import { map, retryWhen, delayWhen, tap } from &#39;rxjs/operators&#39;;<br><br>const source = interval(1000);<br><br>const example = source.pipe(<br>  map(val =&gt; {<br>    if (val &gt; 2) {<br>      throw new Error(&#39;Value too high!&#39;);<br>    }<br>    return val;<br>  }),<br>  retryWhen(errors =&gt;<br>    errors.pipe(<br>      tap(err =&gt; console.log(`Error caught: ${err.message}. Retrying in 1 second...`)),<br>      delayWhen(() =&gt; timer(1000)) // Delay retry by 1 second<br>    )<br>  )<br>);<br><br>example.subscribe(<br>  val =&gt; console.log(val),<br>  err =&gt; console.error(err.message),<br>  () =&gt; console.log(&#39;Complete&#39;)<br>);<br><br>/*<br>Output:<br>0<br>1<br>2<br>Error caught: Value too high!. Retrying in 1 second...<br>0<br>1<br>2<br>Error caught: Value too high!. Retrying in 1 second...<br>... (continues retrying indefinitely with a 1-second delay)<br>*/</pre><p><strong>share:</strong></p><ul><li>Transforms cold Observable into a hot Observable.</li><li>It allows a single execution of an Observable to be shared among multiple subscribers.</li><li>This prevents redundant work and ensures all subscribers receive the same values emitted by the source Observable.</li></ul><pre>import { interval } from &#39;rxjs&#39;;<br>import { share, map } from &#39;rxjs/operators&#39;;<br><br>const source = interval(1000)<br>  .pipe(<br>        map((x: number) =&gt; {<br>            console.log(&#39;Processing: &#39;, x);<br>            return x;<br>        }),<br>        share()<br>);<br><br>source.subscribe(x =&gt; console.log(&#39;subscription 1: &#39;, x));<br>setTimeout(() =&gt; <br>source.subscribe(x =&gt; console.log(&#39;subscription 2: &#39;, x)), 5000<br>)</pre><pre>Processing: 0<br>subscription 1:0<br>subscription 2:0<br>…</pre><p><strong>shareReplay:</strong></p><ul><li>It allows a single execution of an Observable to be shared among multiple subscribers it also replays a specified number of past emitted values to new subscribers.</li><li>This prevents redundant work and ensures all subscribers receive the same values emitted by the source Observable.</li><li>Useful for optimizing performance and avoiding redundant operations, like multiple HTTP requests for the same data.</li></ul><pre>import { of, tap } from &#39;rxjs&#39;;<br>import { shareReplay } from &#39;rxjs/operators&#39;;<br><br>// Simulate an observable that performs a side effect (e.g., an API call)<br>const source$ = of(&#39;Data from source&#39;).pipe(<br>  tap(() =&gt; console.log(&#39;Source observable executed!&#39;)) // This will only be logged once<br>);<br><br>// Apply shareReplay to the source observable<br>// shareReplay(1) means it will replay the last emitted value to new subscribers<br>const sharedSource$ = source$.pipe(<br>  shareReplay(1)<br>);<br><br>console.log(&#39;First subscription:&#39;);<br>sharedSource$.subscribe(data =&gt; console.log(&#39;Subscriber 1:&#39;, data));<br><br>console.log(&#39;Second subscription (after a short delay):&#39;);<br>setTimeout(() =&gt; {<br>  sharedSource$.subscribe(data =&gt; console.log(&#39;Subscriber 2:&#39;, data));<br>}, 100);<br><br>console.log(&#39;Third subscription (after a longer delay, simulating late subscriber):&#39;);<br>setTimeout(() =&gt; {<br>  sharedSource$.subscribe(data =&gt; console.log(&#39;Subscriber 3:&#39;, data));<br>}, 500);</pre><pre>First subscription:<br>Source observable executed!<br>Subscriber 1: Data from source<br>Second subscription (after a short delay):<br>Third subscription (after a longer delay, simulating late subscriber):<br>Subscriber 2: Data from source<br>Subscriber 3: Data from source</pre><p><strong>How can you share a single Observable among multiple subscribers?</strong></p><p>Using share() or shareReplay() operators to share a single Observable among multiple subscribers.</p><p><strong>How can you create a custom operator in RxJS? Write a simple custom operator that doubles the emitted values.</strong></p><pre>import { Observable, pipe } from &#39;rxjs&#39;;<br>import { map } from &#39;rxjs/operators&#39;;<br><br>/**<br> * A custom RxJS operator that doubles each value emitted by the source observable.<br> * @returns A function that takes an Observable and returns a new Observable<br> *          with each emitted value doubled.<br> */<br><br>function doubleValues&lt;T extends number&gt;() {<br>  return function (source: Observable&lt;T&gt;): Observable&lt;number&gt; {<br>    return source.pipe(<br>      map(value =&gt; value * 2)<br>    );<br>  };<br>}<br><br>// Example usage:<br>import { of } from &#39;rxjs&#39;;<br>of(1, 2, 3, 4, 5)<br>  .pipe(<br>    doubleValues()<br>  )<br>  .subscribe(value =&gt; console.log(value));<br><br>// Expected Output:<br>// 2<br>// 4<br>// 6<br>// 8<br>// 10</pre><p><strong>Explain pipe operator in RxJS?</strong></p><ul><li>Pipe operator is used to chain a sequence of operators it improves readability and used to organize a series of transformations (like map, filter, tap) that execute sequentially.</li></ul><pre>import { of } from &#39;rxjs&#39;;<br>import { map, filter } from &#39;rxjs/operators&#39;;<br><br>const numbers = of(1, 2, 3, 4, 5);<br><br>const modifiedNumbers = numbers.pipe(<br>  map(num =&gt; num * 2), // First operator: multiply each number by 2<br>  filter(num =&gt; num &gt; 5) // Second operator: keep only numbers greater than 5<br>);<br><br>modifiedNumbers.subscribe(value =&gt; console.log(value));<br>// Expected output: 6, 8, 10</pre><p><strong>Read More:</strong></p><ul><li><a href="https://dhilip-me.medium.com/angular-interview-preparation-db274264c3a1"><strong>Angular_Basics_Overview</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-lifecycle-hooks-mvvm-architecture-a6cca524ac09"><strong>Angular_Lifecycle_Hooks_And_MVVM_Architecture</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-synchronous-and-asynchronous-behaviors-3e1538f067b2"><strong>Angular_Synchronous_and_Asynchronous_Behaviors</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-pipes-6ccd97de6af1"><strong>Angular_Pipes</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/97941c37d897"><strong>Angular_Forms</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-router-586a84463179"><strong>Angular_Routing</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/angular-interceptors-1c918da59884"><strong>Angular_Interceptors</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-web-workers-1a41d79783d3"><strong>Angular_Web_Workers</strong></a></li><li><a href="https://dhilip-me.medium.com/rxjs-in-angular-63ae9902c4b7"><strong>RxJS_in_Angular</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/69d1fbf8a9fc"><strong>Operators_in_RxJS</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-application-optimization-1f59c0074c42"><strong>Angular_Application_Optimization</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/angular-scenario-based-interview-questions-991e8744fcac"><strong>Angular_Scenario_Based_Interview_Question</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69d1fbf8a9fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Forms]]></title>
            <link>https://dhilip-me.medium.com/angular-forms-97941c37d897?source=rss-bc6e6d0c9eb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/97941c37d897</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-forms]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[template-driven-form]]></category>
            <category><![CDATA[reactive-forms]]></category>
            <dc:creator><![CDATA[Dhilip Kumar]]></dc:creator>
            <pubDate>Mon, 01 Dec 2025 07:42:24 GMT</pubDate>
            <atom:updated>2025-12-11T18:01:55.492Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Explain </strong><strong>FormBuilder?</strong></p><ul><li>FormBuilder is a service provided by the @angular/forms module.</li><li>It simplifies the creation of reactive forms.</li></ul><p>It provides following methods.</p><ol><li><strong>control()</strong></li><li><strong>group()</strong></li><li><strong>array()</strong></li><li><strong>record()</strong></li></ol><p><strong>Explain FormControl?</strong></p><ul><li>FormControl tracks the value and validity status of a form control.</li><li>FormControl can be instantiated with arguments or without arguments. Arguments include initial value, validators etc.</li><li>[formControl] is used to bind the FormControl instances in HTML.</li></ul><pre>firstName = new FormControl(&#39;&#39;, Validators.required);<br>lastName = new FormControl();<br><br>&lt;input [formControl]=&quot;firstName&quot;&gt;<br>&lt;input [formControl]=&quot;lastName&quot;&gt;<br><br>console.log(address.value);<br>console.log(address.status);</pre><p><strong>Explain </strong><strong>FormGroup?</strong></p><p>FormGroup tracks the value and validity state of group of FormControl instances.</p><pre>userForm = new FormGroup({<br>     firstName: new FormControl(&#39;&#39;, [Validators.required]),<br>     lastName: new FormControl(&#39;&#39;, [Validators.required])<br>});<br><br>onFormSubmit() {<br>   console.log(this.userForm.value);<br>   console.log(this.userForm.status);<br>}</pre><pre>&lt;form [formGroup]=&quot;userForm&quot; (ngSubmit)=&quot;onFormSubmit()&quot;&gt;<br>  &lt;p&gt;  First Name: &lt;input formControlName=&quot;firstName&quot;&gt; &lt;/p&gt;<br>  &lt;p&gt;  Last Name: &lt;input formControlName=&quot;lastName&quot;&gt; &lt;/p&gt;<br>  &lt;p&gt;  &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt; &lt;/p&gt;<br>&lt;/form&gt;</pre><p><strong>Explain </strong><strong>FormArray?</strong></p><p>FormArray is used in dynamic forms where the number of input fields can change at runtime, such as lists of items, addresses etc.</p><pre>constructor(private formBuilder: FormBuilder)<br><br>this.userForm = this.formBuilder.group({<br>   firstName: [&#39;&#39;, Validators.required],<br>   lastName: [&#39;&#39;],<br>   teammates: this.formBuilder.array([])<br>});</pre><p>Explain FormRecord?</p><ul><li>FormRecord tracks the value and validity state of group of FormControl instance having <strong>same value type</strong>.</li><li>It is same as FormGroup but FormRecord can have FormControl only with same value type.</li></ul><p>Use FormRecord to create form dynamically. Add form controls using addControl.</p><pre>@Component({<br>   selector: &#39;my-app&#39;,<br>   standalone: true,<br>   imports: [CommonModule, ReactiveFormsModule],<br>   templateUrl: &#39;./my.component.html&#39;<br>})<br><br>export class MyComponent implements OnInit {<br>   userForm: FormRecord;<br>   formData = [<br>      { title: &#39;First Name&#39;, key: &#39;firstName&#39; },<br>      { title: &#39;Last Name&#39;, key: &#39;lastName&#39; }<br>   ];<br><br>   ngOnInit() {<br>      this.userForm = new FormRecord&lt;FormControl&lt;string | null&gt;&gt;({});<br>      this.formData.forEach(data =&gt;<br>         this.userForm.addControl(data.key, new FormControl())<br>      );<br>   }<br><br>   onFormSubmit() {<br>      console.log(this.userForm.value);<br>   }<br>}</pre><pre>&lt;form [formGroup]=&quot;userForm&quot; (ngSubmit)=&quot;onFormSubmit()&quot;&gt;<br><br>    &lt;div *ngFor=&quot;let data of formData&quot;&gt;<br>        {{data.title}}: &lt;input [formControlName]=&quot;data.key&quot;&gt;&lt;br /&gt;<br>    &lt;/div&gt;<br><br>    &lt;button&gt;Submit&lt;/button&gt;<br><br>&lt;/form&gt;</pre><p><strong>How will you add and remove controls on </strong><strong>FormGroup dynamically?</strong></p><p>To add control, use addControl() method with following syntax.</p><pre>addControl(name: string, control: AbstractControl)</pre><pre>this.userForm.addControl(&#39;city&#39;, new FormControl());</pre><p>To remove control, use removeControl() with following syntax.</p><pre>removeControl(name: string)</pre><pre>this.userForm.removeControl(&#39;city&#39;);</pre><p><strong>How to add validation at runtime in reactive form?</strong></p><p>Using setValidators, setAsyncValidators, addValidators, addAsyncValidators.</p><ul><li><strong>setValidators</strong> : Adds sync validators and override if already exists.</li><li><strong>setAsyncValidators</strong> : Adds async validators and override if already exists.</li><li><strong>addValidators</strong> : Adds sync validators and do nothing if already exists.</li><li><strong>addAsyncValidators</strong> : Adds async validators and do nothing if already exists.</li></ul><p>updateValueAndValidity() is called for changes to take effect.</p><p><strong>How to remove validation at runtime in reactive form?</strong></p><p>Using removeValidators, removeAsyncValidators, clearValidators, clearAsyncValidators.</p><ul><li><strong>removeValidators()</strong> : Removes the specified sync validators.</li><li><strong>removeAsyncValidators()</strong> : Removes the specified async validators.</li><li><strong>clearValidators()</strong> : Clears all sync validators.</li><li><strong>clearAsyncValidators()</strong> : Clears all async validators.</li></ul><p>updateValueAndValidity() is called for changes to take effect.</p><pre>get customerName() {<br>  return this.userForm.get(&#39;firstName&#39;);<br>}<br><br>//Instantiate a validator<br>fnMinLength = Validators.minLength(3);<br><br>//Add the validator<br>this.customerName.addValidators([this.fnMinLength]);<br>this.customerName.updateValueAndValidity();<br><br>//Remove the validator<br>this.customerName.removeValidators([this.fnMinLength]);<br>this.customerName.updateValueAndValidity();</pre><p><strong>What is difference between </strong><strong>setValue() and </strong><strong>patchValue()?</strong></p><ol><li>setValue() sets the value of control. When we set value for FormGroup, we need to pass value for all its controls.</li><li>patchValue() patches the value of control. When we patch value for FormGroup, we can pass value for selected controls.</li></ol><p>Example,</p><pre>userForm = this.formBuilder.group({<br> firstName: &#39;&#39;,<br> lastName: &#39;&#39;,  <br> city: &#39;&#39;<br>});</pre><p><strong>Using </strong><strong>setValue() ,</strong></p><pre>this.userForm.setValue({<br> firstName: &#39;Dhilip&#39;,<br> lastName: &#39;Kumar&#39;,  <br> city: &#39;Chennai&#39;<br>});</pre><p><strong>Using </strong><strong>patchValue() ,</strong></p><pre>this.userForm.setValue({<br> firstName: &#39;Dhilip&#39;,<br> city: &#39;Chennai&#39;<br>});</pre><p><strong>How will you mark a form as </strong><strong>touched, </strong><strong>dirty and </strong><strong>pristine programatically?</strong></p><ul><li><strong>markAsTouched()</strong> : marks the control as <em>touched</em>.</li><li><strong>markAllAsTouched()</strong> : marks all the controls of a FormGroup as <em>touched</em>.</li><li><strong>markAsUntouched()</strong> : Marks a control as <em>untouched</em>.</li><li><strong>markAsDirty()</strong> : Marks a control as <em>dirty</em>.</li><li><strong>markAsPristine()</strong> : Marks a control as <em>pristine</em>.</li><li><strong>markAsPending()</strong> : Marks a control as <em>pending</em>.</li></ul><pre>this.userForm.get(&#39;firstName&#39;)?.markAsDirty();<br>this.userForm.markAllAsTouched();</pre><p><strong>markAsDirty() : </strong>A control is “dirty” when its value has changed from its initial state. Used when you programmatically change the value and want to notify that the value has been modified without direct user interaction.</p><p><strong>markAsPristine() : </strong>A control is “pristine” when its value is the same as its initial value, and the user has not interacted with it to change that value.</p><p><strong>markAsPending() : </strong>It indicates that the control is undergoing asynchronous validation, that relies on an external operation (like an HTTP request to a server) that is not yet complete.</p><p><strong>What are the two main types of forms in Angular, and how do they differ?</strong></p><ul><li><strong>Reactive Forms:</strong> Model-driven, suitable for complex forms with custom validation. built using FormControl, FormGroup, and FormArray.</li><li><strong>Template-Driven Forms:</strong> Simple forms, relying on directives like ngModel and ngForm within the template.</li></ul><p><strong>Template driven form example</strong></p><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { BrowserModule } from &#39;@angular/platform-browser&#39;;<br>import { FormsModule } from &#39;@angular/forms&#39;; // Import FormsModule<br>import { AppComponent } from &#39;./app.component&#39;;<br><br>@NgModule({<br>  imports: [<br>    BrowserModule,<br>    FormsModule // Add FormsModule to imports<br>  ],<br>  declarations: [<br>    AppComponent<br>  ],<br>  bootstrap: [AppComponent]<br>})<br><br>export class AppModule { }</pre><pre>&lt;form #userForm=&quot;ngForm&quot; (ngSubmit)=&quot;submit()&quot;&gt;<br><br>  &lt;div&gt;<br>    &lt;label for=&quot;firstName&quot;&gt;First Name&lt;/label&gt;<br>    &lt;input id=&quot;firstName&quot; <br>             name=&quot;firstName&quot;<br>             type=&quot;text&quot;<br>             required<br>             [(ngModel)]=&quot;user.firstName&quot; <br>             #firstName=&quot;ngModel&quot; /&gt;<br>    &lt;div *ngIf=&quot;firstName.errors?.[&#39;required&#39;]&quot;&gt;First Name is required.&lt;/div&gt;<br>  &lt;/div&gt;<br><br>  &lt;div&gt;<br>    &lt;label for=&quot;lastName&quot;&gt;Last Name&lt;/label&gt;<br>    &lt;input id=&quot;lastName&quot;  <br>           name=&quot;lastName&quot; <br>           type=&quot;text&quot; <br>           [(ngModel)]=&quot;user.lastName&quot;<br>           #lastName=&quot;ngModel&quot; /&gt;<br>  &lt;/div&gt;<br><br>  &lt;!-- &lt;button type=&quot;button&quot; [disabled] = &quot;!userForm.form.valid&quot; (click)=&quot;submit()&quot;&gt;Submit&lt;/button&gt; --&gt;<br>  &lt;button type=&quot;submit&quot; [disabled] = &quot;!userForm.form.valid&quot;&gt;Submit&lt;/button&gt;<br><br>&lt;/form&gt;</pre><pre>import { Component } from &quot;@angular/core&quot;;<br><br>@Component({<br>  selector: &quot;my-app&quot;,<br>  templateUrl: &quot;./app.component.html&quot;,<br>  styleUrls: [&quot;./app.component.css&quot;]<br>})<br><br>export class AppComponent {<br>  user = {<br>    firstName: &quot;&quot;,<br>    lastName: &quot;&quot;<br>  };<br><br>  submit() {<br>    console.log(user);<br>  }<br>}</pre><p><strong>Reactive form example</strong></p><pre>// app.module.ts<br>import { NgModule } from &#39;@angular/core&#39;;<br>import { BrowserModule } from &#39;@angular/platform-browser&#39;;<br>import { ReactiveFormsModule } from &#39;@angular/forms&#39;; // Import ReactiveFormsModule<br>import { AppComponent } from &#39;./app.component&#39;;<br><br>@NgModule({<br>  declarations: [<br>    AppComponent<br>  ],<br>  imports: [<br>    BrowserModule,<br>    ReactiveFormsModule // Add to imports<br>  ],<br>  providers: [],<br>  bootstrap: [AppComponent]<br>})<br><br>export class AppModule { }</pre><pre>// app.component.ts<br>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { FormGroup, FormControl, Validators, FormBuilder } from &#39;@angular/forms&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.css&#39;]<br>})<br><br>export class AppComponent implements OnInit {<br>  userForm: FormGroup;<br><br>  constructor(private fb: FormBuilder) {}<br><br>  ngOnInit() {<br>    this.userForm = this.fb.group({<br>      firstName: [&#39;&#39;, Validators.required],<br>      lastName: [&#39;&#39;],<br>    });<br>  }<br><br>  onSubmit() {<br>    if (this.userForm.valid) {<br>      console.log(&#39;Form Submitted!&#39;, this.userForm.value);<br>    }<br>  }<br>}</pre><pre>&lt;!-- app.component.html --&gt;<br>&lt;form [formGroup]=&quot;userForm&quot; (ngSubmit)=&quot;onSubmit()&quot;&gt;<br><br>  &lt;div&gt;<br>    &lt;label for=&quot;firstName&quot;&gt;First Name:&lt;/label&gt;<br>    &lt;input type=&quot;text&quot; id=&quot;firstName&quot; formControlName=&quot;firstName&quot;&gt;<br>    &lt;div *ngIf=&quot;userForm.get(&#39;firstName&#39;)?.errors?.[&#39;required&#39;]&quot;&gt;<br>      First Name is required.<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br><br>  &lt;div&gt;<br>    &lt;label for=&quot;lastName&quot;&gt;Last Name:&lt;/label&gt;<br>    &lt;input type=&quot;text&quot; id=&quot;lastName&quot; formControlName=&quot;lastName&quot;&gt;<br>  &lt;/div&gt;<br><br>  &lt;button type=&quot;submit&quot; [disabled]=&quot;!userForm.valid&quot;&gt;Submit&lt;/button&gt;<br><br>&lt;/form&gt;</pre><p><strong>Reactive form with FormArray example</strong></p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { FormGroup, FormBuilder, FormArray } from &quot;@angular/forms&quot;;<br><br>@Component({<br>  selector: &#39;my-app&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.css&#39;]<br>})<br><br>export class AppComponent {<br>  form: FormGroup;<br><br>  constructor(private fb: FormBuilder) {<br>    this.form = fb.group({<br>      name: [],<br>      address: fb.array([])<br>    })<br>  }<br><br>  addNewAddressGroup() {<br>    const add = this.form.get(&#39;address&#39;) as FormArray;<br>    add.push(this.fb.group({<br>      street: [],<br>      city: []<br>    }))<br>  }<br><br>  deleteAddressGroup(index: number) {<br>    const add = this.form.get(&#39;address&#39;) as FormArray;<br>    add.removeAt(index)<br>  }<br>}</pre><pre>&lt;div [formGroup]=&quot;form&quot;&gt;<br><br>  &lt;div&gt;<br>    &lt;input type=&quot;text&quot; formControlName=&quot;name&quot;&gt;<br>  &lt;/div&gt;<br><br>  &lt;div&gt;<br>    &lt;button (click)=&quot;addNewAddressGroup()&quot;&gt;Add&lt;/button&gt;<br>  &lt;/div&gt;<br><br>  &lt;div *ngFor=&quot;let addressGroup of form.get(&#39;address&#39;).controls;let i = index&quot; [formGroup]=&quot;addressGroup&quot;&gt;<br>      form No : {{i}}<br>        &lt;div&gt;<br>          street &lt;input formControlName=&quot;street&quot;&gt;<br>        &lt;/div&gt;<br>         &lt;div&gt;<br>          city &lt;input formControlName=&quot;city&quot;&gt;<br>        &lt;/div&gt;<br>        &lt;button (click)=&quot;deleteAddressGroup(i)&quot; &gt;Delete - {{i}}&lt;/button&gt;<br>  &lt;/div&gt;<br><br>&lt;/div&gt;</pre><p><a href="https://stackblitz.com/edit/angular-forms-formarray-example?file=src%2Fapp%2Fapp.component.ts">https://stackblitz.com/edit/angular-forms-formarray-example?file=src%2Fapp%2Fapp.component.ts</a></p><p><strong>Nested FormGroup within a reactive form example</strong></p><ul><li>To create a nested FormGroup in a reactive form, define a FormGroup for the parent and nest another FormGroup inside it.</li><li>Like an address FormGroup within a personalInfo FormGroup. In the template, use formGroupName on a div to link the nested FormGroup</li></ul><pre>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { FormGroup, FormControl } from &#39;@angular/forms&#39;;<br><br>@Component({<br>  selector: &#39;app-user-form&#39;,<br>  templateUrl: &#39;./user-form.component.html&#39;,<br>})<br><br>export class UserFormComponent implements OnInit {<br>  userForm!: FormGroup;<br><br>  ngOnInit() {<br>    this.userForm = new FormGroup({<br>      name: new FormControl(&#39;&#39;),<br>      address: new FormGroup({<br>        street: new FormControl(&#39;&#39;),<br>        city: new FormControl(&#39;&#39;)<br>      })<br>    });<br>  }<br>}</pre><pre>&lt;form [formGroup]=&quot;userForm&quot;&gt;<br>  &lt;input type=&quot;text&quot; formControlName=&quot;name&quot; placeholder=&quot;Name&quot;&gt;<br>  &lt;div formGroupName=&quot;address&quot;&gt;<br>    &lt;input type=&quot;text&quot; formControlName=&quot;street&quot; placeholder=&quot;Street&quot;&gt;<br>    &lt;input type=&quot;text&quot; formControlName=&quot;city&quot; placeholder=&quot;City&quot;&gt;<br>  &lt;/div&gt;<br>  &lt;p&gt;Form Value: {{ userForm.value | json }}&lt;/p&gt;<br>&lt;/form&gt;</pre><p><strong>How will you use </strong><strong>valueChanges?</strong></p><p>valueChanges is an observable that emits the <strong>current value</strong> of the control, group, or array whenever that value is programmatically or manually changed.</p><pre>studentForm = this.formBuilder.group({<br>  stdName: [&#39;&#39;, [ Validators.required ]],<br>});<br><br>this.studentForm.get(&#39;stdName&#39;).valueChanges.subscribe(<br>  stdName =&gt; console.log(stdName);<br>);<br><br>this.studentForm.valueChanges.subscribe(student =&gt; {<br> console.log(student.stdName);<br>});</pre><p><strong>How will you use </strong><strong>statusChanges?</strong></p><p>statusChanges is an observable that emits the <strong>validation status</strong> of a FormControl, FormGroup, or FormArray whenever that status changes.</p><pre>studentForm = this.formBuilder.group({<br>  stdName: [&#39;&#39;, [ Validators.required ]],<br>});<br><br>this.studentForm.get(&#39;stdName&#39;).statusChanges.subscribe(<br>  status =&gt; console.log(status);<br>);<br><br>this.studentForm.statusChanges.subscribe(status =&gt; {<br> console.log(status);<br>});</pre><p><strong>What is Typed Forms?</strong></p><p>Forms with type it helps developers prevent runtime errors, ensure consistency, and handle form data more robustly.</p><pre>import { FormGroup, FormControl } from &#39;@angular/forms&#39;;<br><br>interface UserProfile {<br>  firstName: string;<br>  lastName: string;<br>}<br><br>export class UserFormComponent {<br>  userForm = new FormGroup&lt;UserProfile&gt;({<br>    firstName: new FormControl(&#39;&#39;),<br>    lastName: new FormControl(&#39;&#39;)<br>  });<br><br>  onSubmit() {<br>    console.log(this.userForm.value.firstName); // Type-safe access<br>  }<br><br>}</pre><p>In this example, the userForm is explicitly typed with the UserProfile interface, ensuring that all controls within the form group adhere to the defined types. This allows the compiler to detect type mismatches and provides better autocompletion when interacting with form values and controls.</p><p><strong>What are the built-in validators in Angular forms?</strong></p><ul><li>Required</li><li>MinLength</li><li>MaxLength</li><li>Pattern(Validates that the control’s value matches the specified regex pattern)</li></ul><p><strong>How will you perform </strong><strong>required validation?</strong></p><p>In reactive form, we use Validators.required in a FormControl and in template-driven form use required attribute in a form control.</p><p>In reactive form:</p><pre>customerForm = this.formBuilder.group({<br>    customerName: [&#39;&#39;, [Validators.required]]<br>});</pre><p>In template-driven form:</p><pre>&lt;input name=&quot;cname&quot; required #customerName=&quot;ngModel&quot;&gt; <br>&lt;div *ngIf=&quot;customerName.errors?.[&#39;required&#39;]&quot;&gt;<br> Enter  name.<br>&lt;/div&gt;</pre><p><strong>How will you perform </strong><strong>minlength and </strong><strong>maxlength validation?</strong></p><p>In reactive form, we use Validators.minLength and Validators.maxLength in a FormControl and in template-driven form use minlength and maxlength attributes in a form control.</p><p>In reactive form:</p><pre>customerForm = this.formBuilder.group({<br>    customerName: [&#39;&#39;, [Validators.minLength(3), Validators.maxLength(15)]]<br>});</pre><p>In template-driven form:</p><pre>&lt;input name=&quot;cname&quot; minlength=&quot;3&quot; maxlength=&quot;15&quot; #customerName=&quot;ngModel&quot;&gt; <br>&lt;div *ngIf=&quot;customerName.errors?.[&#39;minlength&#39;]&quot;&gt;<br> Min length is 3.<br>&lt;/div&gt;<br>&lt;div *ngIf=&quot;customerName.errors?.[&#39;maxlength&#39;]&quot;&gt;<br> Max length is 15.<br>&lt;/div&gt;</pre><p><strong>How will you perform </strong><strong>min and </strong><strong>max validation?</strong></p><p>In reactive form, we use Validators.min and Validators.max in a FormControl and in template-driven form use min and max attributes in a form control.</p><p>In reactive form:</p><pre>customerForm = this.formBuilder.group({<br>    customerName: [&#39;&#39;, [Validators.min(30), Validators.max(50)]]<br>});</pre><p>In template-driven form:</p><pre>&lt;input name=&quot;cname&quot; min=&quot;30&quot; max=&quot;50&quot; #customerName=&quot;ngModel&quot;&gt; <br>&lt;div *ngIf=&quot;customerName.errors?.[&#39;min&#39;]&quot;&gt;<br> Min value is 30.<br>&lt;/div&gt;<br>&lt;div *ngIf=&quot;customerName.errors?.[&#39;max&#39;]&quot;&gt;<br> Max value is 50.<br>&lt;/div&gt;</pre><p><strong>How will you perform </strong><strong>email validation?</strong></p><p>In reactive form, we use Validators.email in a FormControl and in template-driven form use email attribute in a form control.</p><p>In reactive form:</p><pre>customerForm = this.formBuilder.group({<br>    customerEmail: [&#39;&#39;, [Validators.email]]<br>});</pre><p>In template-driven form:</p><pre>&lt;input name=&quot;cemail&quot; email #customerEmail=&quot;ngModel&quot;&gt; <br>&lt;div *ngIf=&quot;customerEmail.errors?.[&#39;email&#39;]&quot;&gt;<br> Email not valid.<br>&lt;/div&gt;</pre><p><strong>How will you perform </strong><strong>pattern validation?</strong></p><p>In reactive form, we use Validators.pattern in a FormControl and in template-driven form use pattern attribute in a form control.</p><p>In reactive form:</p><pre>cpattern = &#39;^[a-zA-Z0-9]+$&#39;; // Example: alphanumeric characters only<br>// (&#39;^[0-9]{6}$&#39;) Matches exactly 6 digits<br><br>customerForm = this.formBuilder.group({<br>    userName: [&#39;&#39;, [Validators.pattern(this.cpattern)]]<br>});</pre><p>In template-driven form:</p><pre>&lt;input name=&quot;uname&quot; pattern=&#39;^[a-zA-Z0-9]+$&#39; #userName=&quot;ngModel&quot;&gt; <br><br>&lt;div *ngIf=&quot;userName.errors?.[&#39;pattern&#39;]&quot;&gt;<br> Username not valid.<br>&lt;/div&gt;</pre><p><strong>Explain the difference between synchronous and asynchronous validators in Angular forms.</strong></p><p><strong>Synchronous:</strong></p><ul><li>Executes<strong> </strong>immediately when the form control value changes.</li><li><strong>Use Case: </strong>Simple and fast validation logic not involving external resources or asynchronous operations</li></ul><p><strong>Asynchronous</strong>:</p><ul><li>Executes<strong> </strong>Asynchronously, typically when validation depends on external resources or requires a delay.</li><li><strong>Use Case: </strong>Validation that depends on external resources or requires a delay.</li></ul><p><strong>How do you create custom validators in Angular?</strong></p><p>Custom validators can be created by implementing the ValidatorFn interface and using it in the form controls.</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { FormControl, FormGroup, ValidatorFn } from &#39;@angular/forms&#39;;<br><br>@Component({<br>  selector: &#39;my-app&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.css&#39;],<br>})<br><br>export class AppComponent {<br>  form = new FormGroup({<br>    name: new FormControl(&#39;&#39;, this.forbiddenNameValidator()),<br>  });<br><br>  forbiddenNameValidator(): ValidatorFn {<br>    let forbiddenName = &#39;admin&#39;;<br>    return (control) =&gt; {<br>      return forbiddenName == control.value<br>        ? { forbiddenName: { value: control.value } }<br>        : null;<br>    };<br>  }<br>}</pre><pre>&lt;form [formGroup]=&quot;form&quot;&gt;<br>  &lt;input formControlName=&quot;name&quot; placeholder=&quot;Enter Name&quot; /&gt;<br>  &lt;div *ngIf=&quot;form.get(&#39;name&#39;)?.errors?.forbiddenName&quot;&gt;<br>    {{ form.get(&#39;name&#39;).value }} name is forbidden!<br>  &lt;/div&gt;<br>&lt;/form&gt;</pre><p><strong>Output:</strong></p><p>admin name is forbidden!</p><p><strong>Custom Validator for Template-Driven Forms</strong></p><p>Create a directive that implements Validator and provide it with NG_VALIDATORS.</p><pre>import { Directive } from &#39;@angular/core&#39;;<br>import { NG_VALIDATORS, Validator } from &#39;@angular/forms&#39;;<br><br>@Directive({<br>  selector: &#39;[appCustomValidation]&#39;,<br>  providers: [<br>    {<br>      provide: NG_VALIDATORS,<br>      useExisting: CustomValidationDirective,<br>      multi: true,<br>    },<br>  ],<br>})<br><br>export class CustomValidationDirective implements Validator {<br>  constructor() {}<br><br>  validate(control) {<br>    let forbiddenName = &#39;admin&#39;;<br>    return forbiddenName == control.value<br>      ? { forbiddenName: { value: control.value } }<br>      : null;<br>  }<br>}</pre><pre>import { Component, VERSION } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;my-app&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.css&#39;],<br>})<br>export class AppComponent {<br>  model = {<br>    name: &#39;&#39;,<br>  };<br>}</pre><pre>&lt;form&gt;<br>  &lt;input<br>    placeholder=&quot;Enter Name&quot;<br>    [(ngModel)]=&quot;model.name&quot;<br>    name=&quot;name&quot;<br>    #name=&quot;ngModel&quot;<br>    appCustomValidation<br>  /&gt;<br><br>  &lt;div *ngIf=&quot;name.errors?.forbiddenName&quot;&gt;<br>    {{ name.value }} name is forbidden!<br>  &lt;/div&gt;<br>&lt;/form&gt;</pre><p><strong>Output:</strong></p><p>admin name is forbidden!</p><p><strong>How do you create Asynchronous validation in Angular form?</strong></p><p>Asynchronous validation for checking if a username is already taken, using the AsyncValidator interface.</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import {<br>  AsyncValidatorFn,<br>  FormControl,<br>  FormGroup,<br>  Validators,<br>} from &#39;@angular/forms&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;<br>import { map } from &#39;rxjs/operators&#39;;<br><br>@Component({<br>  selector: &#39;my-app&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>})<br><br>export class AppComponent {<br>  form = new FormGroup({<br>    name: new FormControl(&#39;&#39;, Validators.required, this.userValidator()),<br>  });<br><br>  constructor(private http: HttpClient) {}<br><br>  userValidator(): AsyncValidatorFn {<br>    return (control) =&gt; {<br>      return this.http<br>        .get&lt;any&gt;(<br>          &#39;https://jsonplaceholder.typicode.com/users?username=&#39; + control.value<br>        )<br>        .pipe(<br>          map((res) =&gt; {<br>            // if username is already taken<br>            if (res.length) {<br>              // return error<br>              return { userNameExists: true };<br>            }<br>          })<br>        );<br>    };<br>  }<br>}</pre><pre>&lt;form [formGroup]=&quot;form&quot;&gt;<br>  &lt;input formControlName=&quot;name&quot; placeholder=&quot;Enter Name&quot; /&gt;<br><br>  &lt;div *ngIf=&quot;form.get(&#39;name&#39;)?.errors?.userNameExists&quot;&gt;<br>    {{ form.get(&#39;name&#39;).value }} not available!<br>  &lt;/div&gt;<br><br>  &lt;hr /&gt;<br>  &lt;div&gt;NOTE: Bret, Samantha, Karianne are already taken. Try them&lt;/div&gt;<br>&lt;/form&gt;</pre><p><a href="https://stackblitz.com/edit/angular-reactive-forms-async-validator?file=src%2Fapp%2Fapp.component.ts">https://stackblitz.com/edit/angular-reactive-forms-async-validator?file=src%2Fapp%2Fapp.component.ts</a></p><p><strong>What is the difference between ngModel and ngModelGroup?</strong></p><p>Both ngModel and ngModelGroup are part of Angular’s <strong>FormsModule.</strong></p><p><strong>ngModel</strong>:</p><ul><li>ngModel is used to bind input field to a property in the component, typically used with <strong>form controls </strong>it adds form validation like “required”, “min”, “max”, etc.</li><li>It allows <strong>two-way data binding</strong>, It ensures that changes in the model are reflected in the view and vice versa, automatically updating both when either one is modified.</li></ul><p>Example:</p><pre>&lt;input [(ngModel)]=&quot;username&quot; /&gt;</pre><p><strong>ngModelGroup</strong>:</p><ul><li>ngModelGroup is used in <strong>nested forms</strong> or <strong>form groups</strong> to group multiple form controls together. It acts as a container for multiple ngModel.</li></ul><p>Example:</p><pre>&lt;form #form=&quot;ngForm&quot;&gt;<br>  &lt;div ngModelGroup=&quot;address&quot;&gt;<br>    &lt;input ngModel name=&quot;street&quot; /&gt;<br>    &lt;input ngModel name=&quot;city&quot; /&gt;<br>  &lt;/div&gt;<br>&lt;/form&gt;</pre><p><strong>What is difference between (ngModelChange) and (change)?</strong></p><p><strong>ngModelChange:</strong></p><ul><li>ngModelChange is the @Output property of NgModel.</li><li>Works only with ngModel and values are obtained directly by $event.</li></ul><p><strong>change:</strong></p><ul><li>change is the DOM event.</li><li>Works with HTML input elements on value change and gives that value by $event.target.value</li></ul><p><strong>How do you handle form submission in a template-driven form?</strong></p><p>By binding the ngSubmit event of the form to a method in your component.</p><pre>&lt;form (ngSubmit)=&quot;onSubmit(myForm)&quot; #myForm=&quot;ngForm&quot;&gt; <br>&lt;!-- Form controls --&gt; <br>&lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt; &lt;/form&gt;</pre><pre>onSubmit(form: NgForm) { <br>  console.log(&#39;Form submitted:&#39;, form.value); <br>}</pre><p><strong>Read More:</strong></p><ul><li><a href="https://dhilip-me.medium.com/angular-interview-preparation-db274264c3a1"><strong>Angular_Basics_Overview</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-lifecycle-hooks-mvvm-architecture-a6cca524ac09"><strong>Angular_Lifecycle_Hooks_And_MVVM_Architecture</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-synchronous-and-asynchronous-behaviors-3e1538f067b2"><strong>Angular_Synchronous_and_Asynchronous_Behaviors</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-pipes-6ccd97de6af1"><strong>Angular_Pipes</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/97941c37d897"><strong>Angular_Forms</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-router-586a84463179"><strong>Angular_Routing</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/angular-interceptors-1c918da59884"><strong>Angular_Interceptors</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-web-workers-1a41d79783d3"><strong>Angular_Web_Workers</strong></a></li><li><a href="https://dhilip-me.medium.com/rxjs-in-angular-63ae9902c4b7"><strong>RxJS_in_Angular</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/69d1fbf8a9fc"><strong>Operators_in_RxJS</strong></a></li><li><a href="https://dhilip-me.medium.com/angular-application-optimization-1f59c0074c42"><strong>Angular_Application_Optimization</strong></a></li><li><a href="https://medium.com/@dhilipkumar96.me/angular-scenario-based-interview-questions-991e8744fcac"><strong>Angular_Scenario_Based_Interview_Question</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97941c37d897" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>