<?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 The Frontend Fuel on Medium]]></title>
        <description><![CDATA[Stories by The Frontend Fuel on Medium]]></description>
        <link>https://medium.com/@bbcpatra?source=rss-cb91ffefbf8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*E7CsyeUYhWeT5Cn7g3thLg.png</url>
            <title>Stories by The Frontend Fuel on Medium</title>
            <link>https://medium.com/@bbcpatra?source=rss-cb91ffefbf8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 23:45:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bbcpatra/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[Angular Pipe]]></title>
            <link>https://medium.com/@bbcpatra/angular-pipe-f2714247bb58?source=rss-cb91ffefbf8------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2714247bb58</guid>
            <dc:creator><![CDATA[The Frontend Fuel]]></dc:creator>
            <pubDate>Fri, 27 Jun 2025 15:22:03 GMT</pubDate>
            <atom:updated>2025-06-27T15:22:03.556Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pW331gx63c6G00aNmAHD8g.png" /></figure><p>A pipe in Angular is a feature that allows you to transform data in the template. It is typically used to format data before displaying it to the user directly in the HTML view.</p><p>A pipe is a filter or formatter that takes raw data and outputs something more readable or desirable.</p><h4>Why Use Pipes?</h4><ul><li>Reusability (a pipe can be reused across components).</li><li>Separation of concerns (logic stays in the pipe, not in the component).</li><li>Improves readability and maintainability.</li><li>Cleaner templates (you don’t clutter HTML with logic)</li></ul><h4>Custom Pipe Example (Pure Pipe)</h4><p>Let’s say you want to <strong>convert a string to uppercase but add a suffix</strong>:</p><pre>import { Pipe, PipeTransform } from &#39;@angular/core&#39;;<br><br>@Pipe({<br>  name: &#39;appendText&#39;  // Use this name in HTML<br>})<br>export class AppendTextPipe implements PipeTransform {<br>  transform(value: string, suffix: string): string {<br>    return value.toUpperCase() + suffix;<br>  }<br>}</pre><p>In HTML</p><pre>&lt;p&gt;{{ &#39;angular&#39; | appendText:&#39;🔥&#39; }}&lt;/p&gt;</pre><h4>Impure Pipe Example</h4><p>Imagine you have a list that can change without reference change (like push/pop on an array). You might need an <strong>impure pipe</strong> to filter that list dynamically.</p><pre>@Pipe({<br>  name: &#39;filterItems&#39;,<br>  pure: false<br>})<br>export class FilterItemsPipe implements PipeTransform {<br>  transform(items: any[], term: string): any[] {<br>    return items.filter(item =&gt; item.name.includes(term));<br>  }<br>}</pre><pre>&lt;li *ngFor=&quot;let item of items | filterItems:searchTerm&quot;&gt;{{ item.name }}&lt;/li&gt;</pre><h4>Impure Pipe</h4><ul><li>Re-evaluated <strong>on every change detection cycle</strong>.</li><li>It can impact performance.</li><li>Useful for things like filtering mutable arrays or formatting dynamic data like timestamps.</li></ul><h4><strong>Only one argument</strong></h4><p>If your pipe needs <strong>only one argument</strong> (e.g., to find the square root of a number), here’s exactly how it works in Angular.</p><pre>import { Pipe, PipeTransform } from &#39;@angular/core&#39;;<br><br>@Pipe({<br>  name: &#39;sqrt&#39;<br>})<br>export class SqrtPipe implements PipeTransform {<br>  transform(value: number): number {<br>    return Math.sqrt(value);<br>  }<br>}<br><br><br>&lt;p&gt;{{ 49 | sqrt }}&lt;/p&gt;</pre><ul><li>If a pipe takes only one argument, that argument is the value before the | symbol.</li><li>You don’t need extra parameters in the template or transform method.</li></ul><h4>Angular’s Flow:</h4><ul><li>Angular gets items from your component.</li><li>It passes items and searchTerm to transform().</li><li>transform() returns a filtered array.</li><li>*ngFor loops over the filtered array, assigning each element to item.</li></ul><h4>Visual Flow</h4><pre>Component → [items] + [searchTerm]<br>       ↓<br>Pipe: filterItems.transform(items, searchTerm)<br>       ↓<br>Filtered Array → used in *ngFor=&quot;let item of [filtered items]&quot;</pre><h4>Conclusion for Pipes in Angular (Short &amp; Clear)</h4><ul><li>Pipes are used to transform data directly in the template (e.g., format, filter, append).</li><li>Angular provides built-in pipes like <strong>date, uppercase, currency, etc.</strong></li><li>You can create custom pipes for reusable transformation logic.</li><li>Pure pipes (default) run only when input/reference changes — good for performance.</li><li>Impure pipes run on every change detection, which is useful for mutable data like arrays.</li><li>Syntax:</li></ul><pre>{{ value | pipeName:arg1:arg2 }}<br><br>// Internally, it calls: <br>transform(value, arg1, arg2)</pre><pre>import { Pipe, PipeTransform } from &#39;@angular/core&#39;;<br><br>@Pipe({<br>  name: &#39;sqrt&#39;<br>})<br>export class SqrtPipe implements PipeTransform {<br>  transform(value: number): number {<br>    return Math.sqrt(value);<br>  }<br>}</pre><h4>👉 Use pipes to keep your templates <strong>clean</strong>, <strong>readable</strong>, and <strong>efficient</strong>.</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2714247bb58" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is AsyncPipe?]]></title>
            <link>https://medium.com/@bbcpatra/what-is-asyncpipe-52cc520ecfdf?source=rss-cb91ffefbf8------2</link>
            <guid isPermaLink="false">https://medium.com/p/52cc520ecfdf</guid>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[async-pipe]]></category>
            <category><![CDATA[rxjs-operators]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[The Frontend Fuel]]></dc:creator>
            <pubDate>Sun, 04 May 2025 07:40:35 GMT</pubDate>
            <atom:updated>2025-05-04T07:40:35.835Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KsuQFIqsxUKTAyk9VtCStA.png" /></figure><p>The AsyncPipe subscribes to an Observable or a Promise and returns the latest value emitted. It also automatically unsubscribes when the component is destroyed, preventing memory leaks.</p><h4>📘 Real-World Example: Fetching Product List from an API</h4><h4>🛒 Scenario:</h4><p>You’re building a shopping website, and you want to display a list of products fetched from a backend API.</p><h4>✅ Step-by-Step Implementation</h4><ol><li>Create a Product Service</li></ol><pre>// product.service.ts<br>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>export class ProductService {<br>  private apiUrl = &#39;https://fakestoreapi.com/products&#39;;<br><br>  constructor(private http: HttpClient) {}<br><br>  getProducts(): Observable&lt;any[]&gt; {<br>    return this.http.get&lt;any[]&gt;(this.apiUrl);<br>  }<br>}</pre><p>2. <strong>Use the Service in Component</strong></p><pre>// product-list.component.ts<br>import { Component } from &#39;@angular/core&#39;;<br>import { Observable, of } from &#39;rxjs&#39;;<br>import { catchError } from &#39;rxjs/operators&#39;;<br>import { ProductService } from &#39;./product.service&#39;;<br><br>@Component({<br>  selector: &#39;app-product-list&#39;,<br>  templateUrl: &#39;./product-list.component.html&#39;<br>})<br>export class ProductListComponent {<br>  products$: Observable&lt;any[]&gt;;<br>  errorMessage: string = &#39;&#39;;<br><br>  constructor(private productService: ProductService) {<br>    this.products$ = this.productService.getProducts().pipe(<br>      catchError(err =&gt; {<br>        console.error(&#39;Error fetching products:&#39;, err);<br>        this.errorMessage = &#39;Unable to load products at the moment. Please try again later.&#39;;<br>        return of([]); // emit empty list so the template still works<br>      })<br>    );<br>  }<br>}</pre><p>3. Bind Using AsyncPipe in Template</p><pre>&lt;!-- product-list.component.html --&gt;<br>&lt;h2&gt;Available Products&lt;/h2&gt;<br><br>&lt;!-- Error message --&gt;<br>&lt;div *ngIf=&quot;errorMessage&quot; class=&quot;error&quot;&gt;<br>  {{ errorMessage }}<br>&lt;/div&gt;<br><br>&lt;!-- Product list --&gt;<br>&lt;div *ngIf=&quot;products$ | async as products; else loading&quot;&gt;<br>  &lt;div *ngIf=&quot;products.length &gt; 0; else noProducts&quot;&gt;<br>    &lt;div *ngFor=&quot;let product of products&quot;&gt;<br>      &lt;h3&gt;{{ product.title }}&lt;/h3&gt;<br>      &lt;p&gt;{{ product.price | currency }}&lt;/p&gt;<br>      &lt;img [src]=&quot;product.image&quot; alt=&quot;{{ product.title }}&quot; width=&quot;100&quot;&gt;<br>      &lt;hr&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;<br><br>&lt;!-- Loading and No Product Templates --&gt;<br>&lt;ng-template #loading&gt;<br>  &lt;p&gt;Loading products...&lt;/p&gt;<br>&lt;/ng-template&gt;<br><br>&lt;ng-template #noProducts&gt;<br>  &lt;p&gt;No products found.&lt;/p&gt;<br>&lt;/ng-template&gt;</pre><h4>💡 What happens behind the scenes</h4><ul><li>Angular automatically subscribes to products$.</li><li>When data arrives, it’s assigned to products.</li><li>The HTML inside the div is rendered only when data is available.</li><li>Angular also automatically unsubscribes when the component is destroyed.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*78LriGbcL9Aq-9nMGEYbvA.png" /></figure><pre>&lt;div *ngIf=&quot;products$ | async as products; else loading&quot;&gt;</pre><p>👉 Subscribes to products$ using AsyncPipe,<br>👉 If data comes → assigns it to products and shows the block,<br>👉 If no data yet → shows loading template.</p><pre>&lt;div *ngFor=&quot;let product of products&quot;&gt;</pre><p>👉 Loops over the products array (the unwrapped API result),<br>👉 Renders each product.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52cc520ecfdf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Reactive Forms patchValue() and setValue()]]></title>
            <link>https://medium.com/@bbcpatra/angular-reactive-forms-patchvalue-and-setvalue-59228626825f?source=rss-cb91ffefbf8------2</link>
            <guid isPermaLink="false">https://medium.com/p/59228626825f</guid>
            <dc:creator><![CDATA[The Frontend Fuel]]></dc:creator>
            <pubDate>Sat, 03 May 2025 11:51:03 GMT</pubDate>
            <atom:updated>2025-05-03T11:51:03.314Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AnhZX62roVqOunhRb7qytA.png" /></figure><p>In Angular Reactive Forms, patchValue() and setValue() are methods used to update form values. While both are used to set values in a FormGroup, FormControl, or FormArray, they behave differently in how strictly they match the form structure.</p><h4>✅ setValue() — Strict Setter</h4><ul><li>Requires all form fields to be specified.</li><li>Will throw an error if any control is missing.</li></ul><p><strong>Use Case: When you’re confident that the entire form structure matches the object.</strong></p><pre>this.profileForm = new FormGroup({<br>  firstName: new FormControl(&#39;&#39;),<br>  lastName: new FormControl(&#39;&#39;),<br>});<br><br>this.profileForm.setValue({<br>  firstName: &#39;Bhairab&#39;,<br>  lastName: &#39;Patra&#39;<br>});<br><br>✅ Works fine.</pre><pre>this.profileForm.setValue({<br>  firstName: &#39;Bhairab&#39;<br>});<br><br>❌ Error: Must supply a value for form control with name: &#39;lastName&#39;.<br><br></pre><h4>✅ patchValue() — Flexible Setter</h4><ul><li>Allows partial updates.</li><li>Can update one or more controls without error.</li></ul><p><strong>Use Case: When updating only part of the form (e.g., from API or step form).</strong></p><pre>this.profileForm.patchValue({<br>  firstName: &#39;Bhairab&#39;<br>});</pre><p>Updates firstName only, no error about lastName.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59228626825f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Change Detection Mechanisms]]></title>
            <link>https://medium.com/@bbcpatra/angular-change-detection-mechanisms-133e92f6da39?source=rss-cb91ffefbf8------2</link>
            <guid isPermaLink="false">https://medium.com/p/133e92f6da39</guid>
            <dc:creator><![CDATA[The Frontend Fuel]]></dc:creator>
            <pubDate>Fri, 02 May 2025 10:58:20 GMT</pubDate>
            <atom:updated>2025-05-02T10:58:20.444Z</atom:updated>
            <content:encoded><![CDATA[<h4>What is Change Detection in Angular?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A_sIQfZhU3gqXcm4YybplQ.png" /></figure><h4>What is Change Detection in Angular?</h4><p>Change detection is the mechanism by which Angular updates the DOM when application state changes.</p><ul><li>Angular creates a component tree and monitors data-bound properties.</li><li>When values change, Angular re-renders the view accordingly.</li></ul><h4>How does Angular know something has changed?</h4><p>Angular uses <strong>Zone.js</strong> to intercept async operations (e.g., setTimeout, HTTP calls, event listeners) and automatically trigger change detection.</p><h4>Zone.js Under the Hood (Monkey Patching)</h4><p>What is Monkey Patching? Monkey patching means <strong>overriding or modifying built-in APIs</strong> at runtime.</p><h4>How Zone.js Monkey Patches:</h4><p>Zone.js patches async APIs like:</p><ul><li>setTimeout, setInterval</li><li>Promise.then</li><li>DOM events like click, input</li></ul><p>When these are triggered, Zone.js wraps them in <strong>zones</strong> (execution contexts) and notifies Angular that something happened.</p><p>So Angular doesn’t have to manually check for changes — it relies on <strong>Zone.js to detect changes in execution context</strong>.</p><h4>NgZone: Angular’s API to interact with Zones</h4><p><strong>What is NgZone?</strong><br>NgZone is a service that allows Angular to control whether code should run inside or outside Angular’s change detection mechanism.</p><ul><li>It runs all tasks inside Angular’s zone by default.</li><li>You can use <strong>runOutsideAngular()</strong> to opt-out of change detection.</li></ul><h4>Why and When to Use runOutsideAngular()</h4><h4>🚀 Use Case:</h4><p>When you want to perform <strong>high-frequency, non-Angular-related tasks</strong> (like scroll events, timers, animations) <strong>without triggering change detection repeatedly</strong> (which is expensive).</p><p>Benefits:</p><ul><li>Improves performance.</li><li>Avoids unnecessary re-renders.</li></ul><p><strong>Example: Using NgZone and runOutsideAngular()</strong></p><pre>import { Component, NgZone } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-progress-bar&#39;,<br>  template: `<br>    &lt;h3&gt;Progress: {{ progress }}%&lt;/h3&gt;<br>    &lt;button (click)=&quot;start()&quot;&gt;Start&lt;/button&gt;<br>  `<br>})<br>export class ProgressBarComponent {<br>  progress = 0;<br><br>  constructor(private ngZone: NgZone) {}<br><br>  start() {<br>    // Run outside Angular to avoid triggering change detection on every update<br>    this.ngZone.runOutsideAngular(() =&gt; {<br>      this.increaseProgress(() =&gt; {<br>        // Once done, re-enter Angular zone to update UI<br>        this.ngZone.run(() =&gt; {<br>          console.log(&#39;Progress completed!&#39;);<br>        });<br>      });<br>    });<br>  }<br><br>  increaseProgress(doneCallback: () =&gt; void) {<br>    const interval = setInterval(() =&gt; {<br>      this.progress += 1;<br><br>      // This won&#39;t update the UI because we&#39;re outside Angular<br>      if (this.progress &gt;= 100) {<br>        clearInterval(interval);<br>        doneCallback();<br>      }<br>    }, 100);<br>  }<br>}</pre><h4>Change Detection Strategies</h4><ul><li>Default vs OnPush strategy</li><li>Immutability patterns</li><li>Manual change detection triggering</li><li>Performance optimization techniques</li><li>DetectChanges vs MarkForCheck</li></ul><p>Here is a <strong>deep dive explanation</strong> of <strong>Change Detection Strategies</strong> in Angular, specifically useful for <strong>interview preparation</strong>, covering each topic in detail with <strong>real examples</strong> and <strong>reasons for usage</strong>:</p><h3>Default vs OnPush Strategy</h3><h4>Default Strategy</h4><p>Angular’s default change detection strategy checks <strong>every component</strong> in the tree <strong>every time any event or async activity</strong> occurs (e.g., user input, HTTP response, timer).</p><ul><li>It uses <strong>reference and value checking</strong>, and <strong>traverses deeply</strong> into child components.</li><li>Works well but is <strong>less performant</strong> for large applications.</li></ul><h4>OnPush Strategy</h4><p><strong>Angular only checks a component with </strong><strong>OnPush strategy if:</strong></p><ol><li>An <strong>@Input()</strong> reference changes.</li><li>You explicitly trigger change detection (e.g., using detectChanges() or markForCheck()).</li><li>An event inside the component is triggered</li></ol><h4><strong>Why use OnPush?</strong></h4><ul><li>It improves performance by <strong>reducing the number of checks</strong> Angular performs.</li><li>Encourages the use of <strong>immutable objects</strong> (discussed below).</li></ul><h4>Immutability Patterns</h4><h4>Why Immutability?</h4><p>OnPush relies on <strong>object reference</strong> change, so immutability helps Angular <strong>detect changes properly</strong>.</p><pre>this.user = { ...this.user, name: &#39;Jane&#39; }; // triggers OnPush because reference changes</pre><h4>Performance Optimization Techniques</h4><ul><li><strong>Use OnPush</strong> wherever possible.</li><li><strong>Detach</strong> change detection for static/non-updating components:</li></ul><pre>this.cdRef.detach(); // component will not participate in change detection</pre><p><strong>.-TrackBy</strong> in *ngFor to prevent full re-renders</p><pre>&lt;li *ngFor=&quot;let item of items; trackBy: trackById&quot;&gt;{{ item.name }}&lt;/li&gt;</pre><ul><li>Use <strong>async pipe</strong> to automatically subscribe/unsubscribe.</li></ul><h4>detectChanges() vs markForCheck()</h4><p><strong>detectChanges() </strong>: Immediately triggers change detection on the component and its children.<br><strong>markForCheck() </strong>: Marks the component to be checked in the next change detection cycle.</p><p><strong>✅ Use detectChanges():</strong><br>When you want to immediately update the view after a change (e.g., after a setTimeout, manual DOM change).</p><p><strong>✅ Use markForCheck():</strong><br>When using OnPush, and you change data from outside Angular (like a service). This tells Angular:</p><p>“Hey, this component should be checked during the next change detection cycle.”</p><pre>// markForCheck usage in OnPush component<br>this.dataService.getData().subscribe(data =&gt; {<br>  this.data = data;<br>  this.cd.markForCheck();<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*T8FRZ7WyjM0jdcC-auI8FA.png" /></figure><h4>✅ Core Concept of OnPush</h4><p><strong>ChangeDetectionStrategy.OnPush</strong> works based on simple reference comparison between the previous and current @Input() values. Angular does not do a deep check, it only checks if the reference has changed.</p><p><strong>Angular will re-render a component with OnPush strategy only when:</strong></p><ul><li>An @Input() property reference changes (i.e., prev !== next)</li><li>A DOM event happens inside the component</li><li>You call <strong>detectChanges() or markForCheck()</strong></li></ul><h4>Example: Shallow Comparison (prev !== next)</h4><p><strong>child.component.ts (OnPush)</strong></p><pre>@Component({<br>  selector: &#39;app-child&#39;,<br>  template: `Child Name: {{ user.name }}`,<br>  changeDetection: ChangeDetectionStrategy.OnPush<br>})<br>export class ChildComponent {<br>  @Input() user!: { name: string };<br>}</pre><p><strong>parent.component.ts</strong></p><pre>@Component({<br>  selector: &#39;app-parent&#39;,<br>  template: `<br>    &lt;button (click)=&quot;updateName()&quot;&gt;Update Name&lt;/button&gt;<br>    &lt;app-child [user]=&quot;user&quot;&gt;&lt;/app-child&gt;<br>  `<br>})<br>export class ParentComponent {<br>  user = { name: &#39;John&#39; };<br><br>  // This WILL NOT trigger change detection in the child<br>  updateName() {<br>    this.user.name = &#39;Jane&#39;;<br>    // Reference is same; OnPush won&#39;t detect the change<br>  }<br><br>  // This WILL trigger change detection in the child<br>  updateWithNewObject() {<br>    this.user = { ...this.user, name: &#39;Jane&#39; };<br>    // Reference is different; OnPush detects and re-renders<br>  }<br>}</pre><h3>Explanation:</h3><h4>❌ This won’t work:</h4><pre>this.user.name = &#39;Jane&#39;; // same object reference =&gt; no change detected</pre><p>✅ This works:</p><pre>this.user = { ...this.user, name: &#39;Jane&#39; }; // new reference =&gt; OnPush detects change</pre><p>Because Angular’s OnPush strategy internally does</p><pre>if (prevUser !== nextUser) {<br>  // only then re-render child<br>}</pre><h3>Performance Optimization</h3><ul><li>Detaching change detectors</li><li>Custom change detection</li><li>trackBy function implementation</li><li>Pure pipes for memoization</li></ul><h4>Detaching Change Detectors</h4><p><strong>✅ What it is:</strong><br>Angular uses a change detection mechanism to update the DOM when component data changes. Detaching the change detector from a component tells Angular not to check this component (and its subtree) for changes unless we manually trigger it.</p><p>🎯 Why use it:<br>When parts of your app are static or update only occasionally, detaching their change detectors reduces the number of checks Angular must perform, boosting performance.</p><p>🧠 How it works:<br>Use<strong> ChangeDetectorRef.detach() </strong>to stop Angular from checking a component, and detectChanges() or reattach() to manually trigger change detection when needed.</p><p><strong>🧪 Example:</strong></p><pre>import { Component, ChangeDetectorRef } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-heavy&#39;,<br>  template: `&lt;p&gt;Heavy Component: {{ data }}&lt;/p&gt;`,<br>})<br>export class HeavyComponent {<br>  data = &#39;Initial Data&#39;;<br><br>  constructor(private cdRef: ChangeDetectorRef) {}<br><br>  ngOnInit() {<br>    this.cdRef.detach(); // Stops Angular from checking for changes<br>    setTimeout(() =&gt; {<br>      this.data = &#39;Updated Data&#39;;<br>      this.cdRef.detectChanges(); // Manually trigger change detection<br>    }, 5000);<br>  }<br>}</pre><h4>Custom Change Detection Strategy</h4><p><strong>✅ What it is:</strong><br>Angular components default to ChangeDetectionStrategy.Default, which checks the entire component tree. Using ChangeDetectionStrategy.OnPush tells Angular to check for changes only when input properties change or an event is triggered.</p><p><strong>🎯 Why use it:</strong><br>Greatly improves performance by skipping unnecessary checks when data hasn’t changed.</p><p><strong>🧠 How it works:</strong><br>Use immutable data or pure functions. Angular compares @Input() values via reference to determine if change detection is needed.</p><p><strong>🧪 Example:</strong></p><pre>import { Component, Input, ChangeDetectionStrategy } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-optimized&#39;,<br>  template: `&lt;p&gt;{{ user.name }}&lt;/p&gt;`,<br>  changeDetection: ChangeDetectionStrategy.OnPush<br>})<br>export class OptimizedComponent {<br>  @Input() user: { name: string };<br>}</pre><h4>trackBy Function in ngFor</h4><p><strong>✅ What it is:</strong><br>By default, Angular re-renders all elements in an *ngFor loop if the list changes. Using trackBy tells Angular how to uniquely identify list items, so it only updates changed ones.</p><p><strong>🎯 Why use it:</strong><br>Prevents unnecessary re-rendering of DOM elements, improving performance.</p><p><strong>🧠 How it works:</strong><br>Pass a function that returns a unique identifier (like ID or index).</p><p>🧪 Example:</p><pre>&lt;li *ngFor=&quot;let item of items; trackBy: trackById&quot;&gt;{{ item.name }}&lt;/li&gt;<br><br><br>trackById(index: number, item: any): number {<br>  return item.id;<br>}</pre><h4>Pure Pipes for Memoization</h4><p>✅ What it is:<br>Pure pipes are stateless and only re-evaluate when the input changes by reference. Angular calls pure pipes only when inputs change, not on every change detection cycle.</p><p>🎯 Why use it:<br>Minimizes computations, particularly for expensive operations.</p><p>🧠 How it works:<br>By default, custom pipes are pure. You can make them impure by setting pure: false.</p><p><strong>🧪 Example:</strong></p><pre>import { Pipe, PipeTransform } from &#39;@angular/core&#39;;<br><br>@Pipe({<br>  name: &#39;filterUsers&#39;,<br>  pure: true  // Default<br>})<br>export class FilterUsersPipe implements PipeTransform {<br>  transform(users: any[], search: string): any[] {<br>    return users.filter(u =&gt; u.name.includes(search));<br>  }<br>}</pre><pre>&lt;li *ngFor=&quot;let user of users | filterUsers: searchInput&quot;&gt;{{ user.name }}&lt;/li&gt;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=133e92f6da39" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Template Rendering and Binding]]></title>
            <link>https://medium.com/@bbcpatra/template-rendering-and-binding-363a71c04dd1?source=rss-cb91ffefbf8------2</link>
            <guid isPermaLink="false">https://medium.com/p/363a71c04dd1</guid>
            <dc:creator><![CDATA[The Frontend Fuel]]></dc:creator>
            <pubDate>Fri, 02 May 2025 09:33:31 GMT</pubDate>
            <atom:updated>2025-05-02T09:33:31.179Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5SHAR0w2whSKI5yVd_QChQ.png" /></figure><h3><strong>Template Reference Variables</strong></h3><ul><li>Local template references</li><li>@ViewChild/@ViewChildren decorators</li><li>Template reference forwarding deepdive expalntion with example for interv prepartion</li></ul><p>Here’s a deep-dive explanation of Template Reference Variables, Local Template References, @ViewChild/@ViewChildren, and Template Reference Forwarding in Angular — with interview-ready examples and explanations.</p><h4>Template Reference Variables (Local Template References)</h4><p><strong>Definition</strong>:<br>A template reference variable is a way to access DOM elements, components, or directives from the template (HTML) using the # symbol.</p><pre>&lt;input #myInput type=&quot;text&quot; /&gt;<br>&lt;button (click)=&quot;logInput(myInput.value)&quot;&gt;Log&lt;/button&gt;</pre><p><strong>Explanation:</strong></p><ul><li><strong>#myInput </strong>declares a template reference variable.</li><li><strong>myInput.value</strong> accesses the value of the input in the component method.</li></ul><pre>logInput(value: string) {<br>  console.log(value);<br>}</pre><h3>Template Reference Forwarding (Advanced/Trick Concept)</h3><p><strong>Definition</strong>:<br>Forwarding means exposing a template reference variable from a child component to the parent so the parent can access native elements inside the child.</p><h4>Use Case: Expose a child’s input box to the parent</h4><pre>@Component({<br>  selector: &#39;app-child&#39;,<br>  template: `&lt;input #childInput type=&quot;text&quot; /&gt;`<br>})<br>export class ChildComponent {<br>  @ViewChild(&#39;childInput&#39;) inputElement!: ElementRef;<br>}</pre><p><strong>parent.component.ts</strong></p><pre>@Component({<br>  selector: &#39;app-parent&#39;,<br>  template: `<br>    &lt;app-child #childRef&gt;&lt;/app-child&gt;<br>    &lt;button (click)=&quot;focusChildInput(childRef)&quot;&gt;Focus Child Input&lt;/button&gt;<br>  `<br>})<br>export class ParentComponent {<br>  focusChildInput(child: any) {<br>    child.inputElement.nativeElement.focus();<br>  }<br>}</pre><h4>@ViewChild Decorator</h4><p>Definition:<br>@ViewChild is used to get a reference to a single DOM element, directive, or component instance from the template.</p><p><strong>Use Case:</strong> Accessing a child component or native element in the parent component.</p><p>Example:<br><strong>child.component.ts</strong></p><pre>import { Component } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-child&#39;,<br>  template: `&lt;p&gt;Child Component Loaded&lt;/p&gt;`<br>})<br>export class ChildComponent {<br>  greet() {<br>    return &#39;Hello from Child!&#39;;<br>  }<br>}</pre><p><strong>parent.component.ts</strong></p><pre>import { Component, ViewChild, AfterViewInit } from &#39;@angular/core&#39;;<br>import { ChildComponent } from &#39;./child.component&#39;;<br><br>@Component({<br>  selector: &#39;app-parent&#39;,<br>  template: `<br>    &lt;app-child&gt;&lt;/app-child&gt;<br>    &lt;button (click)=&quot;callChild()&quot;&gt;Call Child Method&lt;/button&gt;<br>  `<br>})<br>export class ParentComponent implements AfterViewInit {<br>  @ViewChild(ChildComponent) childComp!: ChildComponent;<br><br>  ngAfterViewInit() {<br>    console.log(this.childComp.greet());<br>  }<br><br>  callChild() {<br>    alert(this.childComp.greet());<br>  }<br>}</pre><p><strong>Key Notes:</strong><br>Use ngAfterViewInit to ensure the child is available and use ! or a null check to avoid undefined errors.</p><h4>@ViewChildren Decorator</h4><p>Definition:<br>✅ What is @ViewChildren in Angular?<br>@ViewChildren is a decorator in Angular that allows you to get references to multiple child components or elements inside a parent component.</p><p>It returns a QueryList, which is like an array that Angular keeps updated when the view changes.</p><p>✅ Real-World Example<br>Let’s say you have a BoxComponent that you use multiple times in a parent component, and you want to call a method on all of them at once.</p><pre>// box.component.ts<br>import { Component } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-box&#39;,<br>  template: `&lt;p&gt;I&#39;m a box component&lt;/p&gt;`<br>})<br>export class BoxComponent {<br>  showMessage() {<br>    console.log(&#39;Box says hello!&#39;);<br>  }<br>}</pre><pre>// dashboard.component.ts<br>import { Component, ViewChildren, QueryList, AfterViewInit } from &#39;@angular/core&#39;;<br>import { BoxComponent } from &#39;./box.component&#39;;<br><br>@Component({<br>  selector: &#39;app-dashboard&#39;,<br>  template: `<br>    &lt;app-box *ngFor=&quot;let item of boxes&quot;&gt;&lt;/app-box&gt;<br>    &lt;button (click)=&quot;notifyAll()&quot;&gt;Notify All Boxes&lt;/button&gt;<br>  `<br>})<br>export class DashboardComponent implements AfterViewInit {<br>  boxes = [1, 2, 3];<br><br>  // 👇 Collects all BoxComponent instances<br>  @ViewChildren(BoxComponent) boxComponents!: QueryList&lt;BoxComponent&gt;;<br><br>  ngAfterViewInit() {<br>    // Called after the view is initialized<br>    this.boxComponents.forEach(box =&gt; box.showMessage());<br>  }<br><br>  notifyAll() {<br>    this.boxComponents.forEach(box =&gt; box.showMessage());<br>  }<br>}<br><br>// Output in Console<br><br>Box says hello!<br>Box says hello!<br>Box says hello!</pre><h3>Content Projection</h3><ul><li>Single-slot projection</li><li>Multi-slot projection with ng-content[select]</li><li>Conditional content projection</li></ul><h4><strong>What is Content Projection?</strong></h4><p>Content Projection allows you to pass HTML content from a parent component into a child component’s template.</p><p><strong>Angular provides this using the &lt;ng-content&gt; directive.</strong></p><p><strong>Single-slot Content Projection</strong><br>Use Case: Used when you want to pass a block of content (like HTML) into a component.</p><p><strong>Example:</strong><br><strong>Parent Component Template</strong></p><pre>&lt;app-alert-box&gt;<br>  &lt;strong&gt;Warning:&lt;/strong&gt; This action is irreversible!<br>&lt;/app-alert-box&gt;</pre><p><strong>Child Component</strong></p><pre>@Component({<br>  selector: &#39;app-alert-box&#39;,<br>  template: `<br>    &lt;div class=&quot;alert&quot;&gt;<br>      &lt;ng-content&gt;&lt;/ng-content&gt; &lt;!-- 👈 Single-slot projection --&gt;<br>    &lt;/div&gt;<br>  `,<br>  styles: [`.alert { border: 1px solid red; padding: 10px; }`]<br>})<br>export class AlertBoxComponent {}</pre><h4><strong>Multi-slot Content Projection with select</strong></h4><h4>Use Case:</h4><p>When you want to project different types of content to different places.</p><p><strong>Parent Component Template</strong></p><pre>&lt;app-dialog&gt;<br>  &lt;h2 title&gt;Title Here&lt;/h2&gt;<br>  &lt;p body&gt;Body content goes here.&lt;/p&gt;<br>&lt;/app-dialog&gt;</pre><p>app-dialog.component.html</p><pre>&lt;div class=&quot;dialog&quot;&gt;<br>  &lt;div class=&quot;dialog-title&quot;&gt;<br>    &lt;ng-content select=&quot;[title]&quot;&gt;&lt;/ng-content&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;dialog-body&quot;&gt;<br>    &lt;ng-content select=&quot;[body]&quot;&gt;&lt;/ng-content&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><h3>Conditional Content Projection</h3><p><strong>What is Conditional Content Projection?</strong><br>In Angular, content projection with <strong>&lt;ng-content&gt;</strong> allows a parent component to inject content into a child component. However, Angular doesn’t natively support projecting content conditionally based on logic within the child component.</p><p><strong>But we can simulate conditional content projection using *ngIf, @Input(), and ng-content’s select attribute.</strong></p><p><strong>Why Use Conditional Projection?</strong></p><ul><li>Show different projected content based on a condition.</li><li>Render a part of the projected content only if an input is true or false.</li><li>Toggle between two sections of projected content.</li></ul><p><strong>Parent Component Template</strong></p><pre>&lt;app-alert [isError]=&quot;true&quot;&gt;<br>  &lt;div error&gt;<br>    &lt;strong&gt;Error:&lt;/strong&gt; Something went wrong.<br>  &lt;/div&gt;<br>  &lt;div success&gt;<br>    &lt;strong&gt;Success:&lt;/strong&gt; Operation completed successfully.<br>  &lt;/div&gt;<br>&lt;/app-alert&gt;<br><br>&lt;app-alert [isError]=&quot;false&quot;&gt;<br>  &lt;div error&gt;<br>    &lt;strong&gt;Error:&lt;/strong&gt; This should not show.<br>  &lt;/div&gt;<br>  &lt;div success&gt;<br>    &lt;strong&gt;Success:&lt;/strong&gt; Everything is good!<br>  &lt;/div&gt;<br>&lt;/app-alert&gt;</pre><p><strong>Child Component</strong></p><pre>import { Component, Input } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-alert&#39;,<br>  templateUrl: &#39;./alert.component.html&#39;,<br>  styleUrls: [&#39;./alert.component.css&#39;]<br>})<br>export class AlertComponent {<br>  @Input() isError = false;<br>}<br><br><br>&lt;div class=&quot;alert&quot;&gt;<br>  &lt;ng-content *ngIf=&quot;isError&quot; select=&quot;[error]&quot;&gt;&lt;/ng-content&gt;<br>  &lt;ng-content *ngIf=&quot;!isError&quot; select=&quot;[success]&quot;&gt;&lt;/ng-content&gt;<br>&lt;/div&gt;</pre><h4>What Happens Here</h4><ul><li>The parent provides both [error] and [success] blocks.</li><li>The child component chooses which one to render based on the isError input.</li><li>*ngIf=”isError” ensures only the [error] content is shown when the condition is true.</li><li>*ngIf=”!isError” shows the [success] content when the condition is false.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=363a71c04dd1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Directives]]></title>
            <link>https://medium.com/@bbcpatra/angular-directives-0c6b0b49e2a9?source=rss-cb91ffefbf8------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c6b0b49e2a9</guid>
            <category><![CDATA[directives-in-angular]]></category>
            <category><![CDATA[directives]]></category>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[The Frontend Fuel]]></dc:creator>
            <pubDate>Fri, 02 May 2025 08:19:28 GMT</pubDate>
            <atom:updated>2025-05-02T08:24:50.403Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uDgnzHLw-2_dHKGu5WmcLg.png" /></figure><h3>Directive composition and reuse</h3><p>In Angular, directive composition and reuse refer to how you can build modular, reusable UI logic by creating and combining custom directives across components. This approach helps to separate concerns, improve code maintainability, and encourage DRY (Don’t Repeat Yourself) principles.</p><h4>What is a Directive in Angular?</h4><p>A directive is a class with a <strong>@Directive()</strong> decorator that adds behavior to elements in your Angular templates.</p><p><strong>There are three types of directives:</strong></p><ol><li>Component — technically a directive with a template.</li><li>Structural Directive — changes the DOM layout (*ngIf, *ngFor).</li><li>Attribute Directive — changes the appearance or behavior of an element ([ngClass], [ngStyle]).</li></ol><h4>✅ Use Case: Directive Reuse and Composition</h4><p>Let’s go through a <strong>real-world example</strong>: You want to highlight an input when it’s focused and show a tooltip on hover. Instead of repeating code in every component, you create <strong>two reusable attribute directives</strong>.</p><p><strong>Create HighlightOnFocusDirective</strong></p><pre>// highlight-on-focus.directive.ts<br>import { Directive, ElementRef, HostListener, Renderer2 } from &#39;@angular/core&#39;;<br><br>@Directive({<br>  selector: &#39;[appHighlightOnFocus]&#39;<br>})<br>export class HighlightOnFocusDirective {<br>  constructor(private el: ElementRef, private renderer: Renderer2) {}<br><br>  @HostListener(&#39;focus&#39;) onFocus() {<br>    this.renderer.setStyle(this.el.nativeElement, &#39;background-color&#39;, &#39;lightyellow&#39;);<br>  }<br><br>  @HostListener(&#39;blur&#39;) onBlur() {<br>    this.renderer.removeStyle(this.el.nativeElement, &#39;background-color&#39;);<br>  }<br>}</pre><p><strong>Create TooltipDirective</strong></p><pre>// tooltip.directive.ts<br>import { Directive, ElementRef, HostListener, Input, Renderer2 } from &#39;@angular/core&#39;;<br><br>@Directive({<br>  selector: &#39;[appTooltip]&#39;<br>})<br>export class TooltipDirective {<br>  @Input(&#39;appTooltip&#39;) tooltipText = &#39;&#39;;<br>  tooltip: HTMLElement;<br><br>  constructor(private el: ElementRef, private renderer: Renderer2) {}<br><br>  @HostListener(&#39;mouseenter&#39;) onMouseEnter() {<br>    this.tooltip = this.renderer.createElement(&#39;span&#39;);<br>    this.tooltip.innerText = this.tooltipText;<br>    this.renderer.appendChild(this.el.nativeElement, this.tooltip);<br>    this.renderer.setStyle(this.tooltip, &#39;position&#39;, &#39;absolute&#39;);<br>    this.renderer.setStyle(this.tooltip, &#39;background&#39;, &#39;black&#39;);<br>    this.renderer.setStyle(this.tooltip, &#39;color&#39;, &#39;white&#39;);<br>  }<br><br>  @HostListener(&#39;mouseleave&#39;) onMouseLeave() {<br>    if (this.tooltip) {<br>      this.renderer.removeChild(this.el.nativeElement, this.tooltip);<br>    }<br>  }<br>}</pre><p><strong>Use Directives Together (Composition)</strong></p><pre>&lt;!-- app.component.html --&gt;<br>&lt;input<br>  type=&quot;text&quot;<br>  placeholder=&quot;Enter name&quot;<br>  appHighlightOnFocus<br>  appTooltip=&quot;Enter your full name&quot;<br>/&gt;</pre><p><strong>Here, the input element is now:</strong></p><ul><li>Highlighted on focus (from HighlightOnFocusDirective)</li><li>Showing tooltip on hover (from TooltipDirective)</li></ul><p>You’ve composed functionality by stacking directives on a single element.</p><h4>How It Works Under the Hood</h4><ul><li>Angular identifies all matching directives on a DOM element.</li><li>For each directive, Angular creates an instance and applies:</li><li>Lifecycle hooks (ngOnInit, etc.)</li><li>Input bindings</li><li>Event listeners via @HostListener</li></ul><p>All directives share the same DOM element but can apply separate logic independently.</p><h3>Export as and template variables</h3><p>In Angular, exportAs and template variables are powerful tools used in templates to refer to and interact with components, directives, or other elements.</p><h4>exportAs in Angular</h4><p>exportAs is a property you can define in a directive or component’s decorator (<a href="http://twitter.com/Directive">@Directive</a> or <a href="http://twitter.com/Component">@Component</a>). It allows you to assign a <strong>custom </strong>name that can be used as a reference to the directive/component in the template via a template reference variable.</p><p><strong>Custom Directive Example</strong></p><pre>import { Directive } from &#39;@angular/core&#39;;<br><br>@Directive({<br>  selector: &#39;[appToggle]&#39;,<br>  exportAs: &#39;toggle&#39;  // 👈 This is key<br>})<br>export class ToggleDirective {<br>  isOpen = false;<br><br>  toggle() {<br>    this.isOpen = !this.isOpen;<br>  }<br>}</pre><p><strong>Usage in Template</strong></p><pre>&lt;div appToggle #myToggle=&quot;toggle&quot;&gt;<br>  &lt;p *ngIf=&quot;myToggle.isOpen&quot;&gt;Toggled content!&lt;/p&gt;<br>  &lt;button (click)=&quot;myToggle.toggle()&quot;&gt;Toggle&lt;/button&gt;<br>&lt;/div&gt;</pre><ul><li><strong>#myToggle=”toggle” :</strong> binds the directive instance (exported as toggle) to the variable myToggle</li><li>You can now call methods or access properties from the directive</li></ul><h4>Template Reference Variables (#variableName)</h4><p>Template variables are declared using #varName and can be used to refer to a DOM element, directive, or component instance within the template.</p><p><strong>Using exportAs with Template Variable</strong><br>✅ Step 1: Directive with exportAs</p><pre>import { Directive, HostListener } from &#39;@angular/core&#39;;<br><br>@Directive({<br>  selector: &#39;[appHighlight]&#39;,<br>  exportAs: &#39;highlightDir&#39;<br>})<br>export class HighlightDirective {<br>  private isHighlighted = false;<br><br>  toggleHighlight() {<br>    this.isHighlighted = !this.isHighlighted;<br>    console.log(`Highlight is now: ${this.isHighlighted}`);<br>  }<br>}</pre><p>✅ Step 2: Use in Template</p><pre>&lt;!-- Apply directive and export it with #highlight --&gt;<br>&lt;div appHighlight #highlight=&quot;highlightDir&quot;&gt;<br>  Hover over me!<br>&lt;/div&gt;<br><br>&lt;!-- Button triggers a method on the directive --&gt;<br>&lt;button (click)=&quot;highlight.toggleHighlight()&quot;&gt;Toggle Highlight&lt;/button&gt;</pre><h4><strong>What’s Happening Here</strong></h4><ul><li><strong>#highlight=”highlightDir”</strong> → binds to the directive instance using the name <strong>highlightDir </strong>defined in <strong>exportAs</strong>.</li><li><strong>highlight.toggleHighlight()</strong> → calls the directive method directly from the template.</li></ul><h4>Example: Using NgForm (Built-in exportAs)</h4><p>Angular’s built-in directives like NgForm, NgModel, and ngModelGroup also use exportAs.</p><pre>&lt;form #f=&quot;ngForm&quot; (ngSubmit)=&quot;onSubmit(f)&quot;&gt;<br>  &lt;input name=&quot;username&quot; ngModel required /&gt;<br>  &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>&lt;/form&gt;<br><br>&lt;p *ngIf=&quot;f.valid&quot;&gt;Form is valid!&lt;/p&gt;</pre><p><strong>Explanation:</strong><br><em>NgForm is exported as ngForm.</em></p><p>#f=”ngForm” gives you access to the form’s validity, values, etc.</p><h4>Summary</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*nyKVAI7fEp98yuxb746tIQ.png" /></figure><h3>Multi-slot transclusion and directive communication</h3><p>In Angular, <strong>multi-slot transclusion</strong> and <strong>directive communication</strong> are advanced topics that often go hand-in-hand when building reusable and dynamic components. Let’s deep dive into both</p><h4>Multi-slot Transclusion (Using ng-content)</h4><p><strong>📣 What is Transclusion?</strong><br>Transclusion allows you to pass content from a parent component into a child component. Angular provides this with <strong>&lt;ng-content&gt;.</strong></p><p><strong>📣 What is Multi-slot Transclusion?</strong><br>Instead of having a single slot (&lt;ng-content&gt;&lt;/ng-content&gt;), you can define named slots to place content in specific areas using the <strong>select attribute.</strong></p><h4>Multi-slot Transclusion</h4><p>card.component.html (Child Component)</p><pre>// card.component.html<br>&lt;div class=&quot;card&quot;&gt;<br>  &lt;div class=&quot;card-header&quot;&gt;<br>    &lt;ng-content select=&quot;[card-header]&quot;&gt;&lt;/ng-content&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;card-body&quot;&gt;<br>    &lt;ng-content select=&quot;[card-body]&quot;&gt;&lt;/ng-content&gt;<br>  &lt;/div&gt;<br>  &lt;div class=&quot;card-footer&quot;&gt;<br>    &lt;ng-content select=&quot;[card-footer]&quot;&gt;&lt;/ng-content&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;<br><br><br>//card.component.ts<br>import { Component } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-card&#39;,<br>  templateUrl: &#39;./card.component.html&#39;,<br>  styleUrls: [&#39;./card.component.css&#39;]<br>})<br>export class CardComponent {}</pre><p><strong>Usage in Parent Component</strong></p><pre>&lt;app-card&gt;<br>  &lt;div card-header&gt;Header Content&lt;/div&gt;<br>  &lt;div card-body&gt;Main Content&lt;/div&gt;<br>  &lt;div card-footer&gt;Footer Content&lt;/div&gt;<br>&lt;/app-card&gt;</pre><p>The select in <strong>ng-content</strong> works like a CSS selector. The content with the matching attribute will be projected into that slot.</p><h4>Directive Communication</h4><p><strong>What is Directive Communication?</strong><br>It involves sharing data or behavior between a directive and a component, or between multiple directives. Common scenarios include using <a href="http://twitter.com/Input">@Input</a>(), <a href="http://twitter.com/Output">@Output</a>(),</p><p><strong>Example Directive Communicating with a Component</strong></p><pre>import { Directive, ElementRef, HostListener, Input } from &#39;@angular/core&#39;;<br><br>@Directive({<br>  selector: &#39;[appHighlight]&#39;<br>})<br>export class HighlightDirective {<br>  @Input() appHighlight = &#39;yellow&#39;;<br><br>  constructor(private el: ElementRef) {}<br><br>  @HostListener(&#39;mouseenter&#39;) onMouseEnter() {<br>    this.highlight(this.appHighlight);<br>  }<br><br>  @HostListener(&#39;mouseleave&#39;) onMouseLeave() {<br>    this.highlight(null);<br>  }<br><br>  private highlight(color: string | null) {<br>    this.el.nativeElement.style.backgroundColor = color;<br>  }<br>}</pre><p>Usage in Template</p><pre>&lt;p [appHighlight]=&quot;&#39;lightblue&#39;&quot;&gt;Hover over me to see highlight&lt;/p&gt;</pre><h4>Single-slot Projection in Angular (a.k.a. Content Projection)</h4><p>Single-slot projection allows you to pass content (HTML or components) from a parent component into a specific location in a child component using the &lt;ng-content&gt; tag.</p><p>Think of &lt;ng-content&gt; as a placeholder in your child component, where you can “project” HTML from the parent.</p><p><strong>Basic Example</strong></p><pre>// Child Component: alert-box.component.ts<br>@Component({<br>  selector: &#39;app-alert-box&#39;,<br>  template: `<br>    &lt;div class=&quot;alert&quot;&gt;<br>      &lt;ng-content&gt;&lt;/ng-content&gt; &lt;!-- 👈 Single-slot projection --&gt;<br>    &lt;/div&gt;<br>  `,<br>  styles: [`.alert { border: 1px solid red; padding: 10px; }`]<br>})<br>export class AlertBoxComponent {}<br><br><br>// Parent Component Template<br>&lt;app-alert-box&gt;<br>  &lt;strong&gt;Warning:&lt;/strong&gt; This action is irreversible!<br>&lt;/app-alert-box&gt;</pre><h3>What is Context Projection in Angular and How Does it Work?</h3><p>Context Projection in Angular refers to passing contextual data from a parent component to the projected content inside a child component. It is an enhancement of content projection using &lt;ng-template&gt; and ngTemplateOutlet, allowing dynamic and flexible templates with data binding.</p><p>While basic content projection (&lt;ng-content&gt;) passes static content, context projection allows you to inject dynamic data (context) into that content.</p><p>Context projection in Angular is a technique where a parent component passes a TemplateRef and a context object to a child component, allowing the child to render dynamic content with bound data using ngTemplateOutlet.</p><p><strong>Example: Context Projection in Angular</strong></p><p>We want to create a <strong>reusable card component</strong> that can display <strong>any content</strong> passed from a parent with dynamic data like a title and message.</p><p><strong>Create the Child Component (card.component.ts)</strong><br>This component receives:</p><ul><li>A TemplateRef (<a href="http://twitter.com/Input">@Input</a>() template)</li><li>A context object (<a href="http://twitter.com/Input">@Input</a>() context) to bind data dynamically</li></ul><pre>import { Component, Input, TemplateRef } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-card&#39;,<br>  template: `<br>    &lt;div class=&quot;card&quot;&gt;<br>      &lt;ng-container *ngTemplateOutlet=&quot;template; context: context&quot;&gt;&lt;/ng-container&gt;<br>    &lt;/div&gt;<br>  `,<br>  styles: [`<br>    .card {<br>      border: 1px solid #ccc;<br>      padding: 10px;<br>      margin: 10px;<br>    }<br>  `]<br>})<br>export class CardComponent {<br>  @Input() template!: TemplateRef&lt;any&gt;;<br>  @Input() context: any = {};<br>}</pre><p><strong>Use the Card Component in the Parent (app.component.html)</strong></p><pre>&lt;app-card <br>  [template]=&quot;myCardTemplate&quot; <br>  [context]=&quot;{ $implicit: &#39;Angular&#39;, subtitle: &#39;Framework for Web&#39; }&quot;&gt;<br>&lt;/app-card&gt;<br><br>&lt;ng-template #myCardTemplate let-title let-subtitle=&quot;subtitle&quot;&gt;<br>  &lt;h2&gt;{{ title }}&lt;/h2&gt;<br>  &lt;p&gt;{{ subtitle }}&lt;/p&gt;<br>&lt;/ng-template&gt;</pre><p><strong>Explanation:</strong></p><ul><li>myCardTemplate is the actual content to render inside the app-card component.</li><li>let-title binds to $implicit which is passed as ‘Angular’.</li><li>let-subtitle=”subtitle” binds to the subtitle property in the context.</li><li>ngTemplateOutlet renders the content with the passed-in data.</li></ul><p>Context projection lets us pass a TemplateRef and a context object to a child component so it can render dynamic content using ngTemplateOutlet, enabling clean, reusable, and flexible component design.</p><h3>@HostListener and @HostBinding</h3><p>In Angular, @HostListener and @HostBinding are powerful decorators provided by the @angular/core package. They allow you to interact directly with the host element of a directive or component. Here’s a deep dive into each, including how they work and examples.</p><p><strong>@HostListener — Listening to Host Events</strong></p><p>✅ Purpose: @HostListener allows your directive or component to listen to DOM events on the host element.</p><pre>@HostListener(&#39;eventName&#39;, [&#39;eventArgs&#39;])<br>methodName(args) {<br>  // logic<br>}<br><br><br>import { Directive, HostListener } from &#39;@angular/core&#39;;<br><br>@Directive({<br>  selector: &#39;[appHighlight]&#39;<br>})<br>export class HighlightDirective {<br><br>  @HostListener(&#39;mouseenter&#39;) onMouseEnter() {<br>    console.log(&#39;Mouse entered!&#39;);<br>  }<br><br>  @HostListener(&#39;mouseleave&#39;) onMouseLeave() {<br>    console.log(&#39;Mouse left!&#39;);<br>  }<br><br>  @HostListener(&#39;click&#39;, [&#39;$event&#39;]) onClick(event: MouseEvent) {<br>    console.log(&#39;Clicked!&#39;, event);<br>  }<br>}</pre><h4>What’s Happening?</h4><ul><li>When you hover over an element with appHighlight, it triggers mouseenter and mouseleave.</li><li>When you click on the element, it logs the event object.</li><li>Angular internally binds the events to the host DOM element.</li></ul><p><strong>@HostBinding — Binding to Host Properties or Attributes</strong></p><p>✅ Purpose: @HostBinding allows you to bind a property or attribute of the host element to a value in the directive/component class.</p><pre>import { Directive, HostBinding, HostListener } from &#39;@angular/core&#39;;<br><br>@Directive({<br>  selector: &#39;[appHighlight]&#39;<br>})<br>export class HighlightDirective {<br><br>  @HostBinding(&#39;style.backgroundColor&#39;) bgColor: string;<br><br>  @HostListener(&#39;mouseenter&#39;) onMouseEnter() {<br>    this.bgColor = &#39;lightblue&#39;;<br>  }<br><br>  @HostListener(&#39;mouseleave&#39;) onMouseLeave() {<br>    this.bgColor = &#39;transparent&#39;;<br>  }<br>}</pre><p><strong>What’s Happening?</strong><br>When the mouse enters, it changes the background color of the host element.</p><ul><li>@HostBinding(‘style.backgroundColor’) binds the style to a class property.</li><li>You don’t need to access the native element manually via ElementRef.</li></ul><h4>Directive That Highlights and Toggles Classes</h4><pre>import { Directive, HostBinding, HostListener } from &#39;@angular/core&#39;;<br><br>@Directive({<br>  selector: &#39;[appToggleHighlight]&#39;<br>})<br>export class ToggleHighlightDirective {<br>  private isHighlighted = false;<br><br>  @HostBinding(&#39;class.highlight&#39;) get highlightClass() {<br>    return this.isHighlighted;<br>  }<br><br>  @HostListener(&#39;click&#39;)<br>  toggleHighlight() {<br>    this.isHighlighted = !this.isHighlighted;<br>  }<br>}</pre><p>Add CSS</p><pre>.highlight {<br>  background-color: yellow;<br>  transition: background-color 0.3s;<br>}</pre><p><strong>How It Works:</strong></p><ul><li>Clicking the element toggles the highlight class.</li><li>The directive manages the class binding with a getter and <a href="http://twitter.com/HostBinding">@HostBinding</a>.</li></ul><h3>ElementRef, Renderer2, and direct DOM manipulation</h3><p><strong>✅ ElementRef : </strong>Used to access the native DOM element directly in Angular.</p><ul><li>Usage: el.nativeElement</li><li>Caution: Avoid direct access as it can break Angular’s rendering and security (XSS risks).</li></ul><p><strong>✅ Renderer2 : </strong>Angular’s safe and platform-independent way to manipulate the DOM.</p><ul><li>Usage: renderer.setStyle(), renderer.addClass(), etc.</li><li>Preferred over ElementRef for updating DOM elements.</li></ul><p><strong>❌ Direct DOM Manipulation</strong>: Accessing DOM via document.getElementById() or nativeElement directly.</p><ul><li>Not recommended in Angular.</li><li>Breaks SSR, testing, and security.</li></ul><p>Here’s a combined example using ElementRef, Renderer2, and @HostListener, along with an explanation of how it works.</p><pre>import { Directive, ElementRef, HostListener, Renderer2 } from &#39;@angular/core&#39;;<br><br>@Directive({<br>  selector: &#39;[appHoverHighlight]&#39;<br>})<br>export class HoverHighlightDirective {<br><br>  constructor(private el: ElementRef, private renderer: Renderer2) {}<br><br>  @HostListener(&#39;mouseenter&#39;) onMouseEnter() {<br>    this.renderer.setStyle(this.el.nativeElement, &#39;backgroundColor&#39;, &#39;lightyellow&#39;);<br>    this.renderer.setStyle(this.el.nativeElement, &#39;cursor&#39;, &#39;pointer&#39;);<br>  }<br><br>  @HostListener(&#39;mouseleave&#39;) onMouseLeave() {<br>    this.renderer.removeStyle(this.el.nativeElement, &#39;backgroundColor&#39;);<br>    this.renderer.removeStyle(this.el.nativeElement, &#39;cursor&#39;);<br>  }<br>}</pre><p><strong>💡 How It Works</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*-cHlvkFGwoBMyFMS97C-Aw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c6b0b49e2a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementation of tap, take, and takeUntil from RxJS in Angular.]]></title>
            <link>https://medium.com/@bbcpatra/implementation-of-tap-take-and-takeuntil-from-rxjs-in-angular-92a5e4eb8686?source=rss-cb91ffefbf8------2</link>
            <guid isPermaLink="false">https://medium.com/p/92a5e4eb8686</guid>
            <dc:creator><![CDATA[The Frontend Fuel]]></dc:creator>
            <pubDate>Sun, 06 Apr 2025 09:03:15 GMT</pubDate>
            <atom:updated>2025-04-06T09:03:15.689Z</atom:updated>
            <content:encoded><![CDATA[<h4>Real-World Angular Use Case: RxJS Operators</h4><p>Imagine you’re building a <strong>user profile component</strong> that loads user data from an API. You also want to:</p><ul><li>Log values for debugging (tap)</li><li>Unsubscribe after 1 value (take)</li><li>Unsubscribe when component is destroyed (takeUntil)</li></ul><h4>🔥 <strong>Flow</strong></h4><p>In Angular apps, we commonly use tap for logging or triggering side effects like analytics.</p><p>Use take(1) when I need only the first emission — like in most HTTP calls. For memory management, especially with long-lived streams like valueChanges.</p><p>Use takeUntil(this.destroy$) in combination with ngOnDestroy to ensure cleanup.</p><h3>tap – For Side Effects</h3><h4>🧪 What is it?</h4><ul><li>tap() lets you <strong>peek into</strong> the observable stream without changing the values.</li><li>It’s mainly used for <strong>logging</strong>, <strong>debugging</strong>, or performing <strong>side effects</strong> (like showing a loader or sending analytics).</li></ul><h4>🧪 Use Case Example</h4><ul><li>Log every HTTP response for debugging.</li><li>Show a spinner while data is loading.</li></ul><h4>🧪 Example:</h4><pre>of(&#39;userData&#39;).pipe(<br>  tap(data =&gt; console.log(&#39;Received data:&#39;, data))<br>).subscribe();</pre><p>I use tap() for debugging or performing actions like showing/hiding loaders without affecting the data stream.</p><h3>take – Take Limited Emissions</h3><h4>🧪 What is it?</h4><ul><li>take(n) completes the observable <strong>after emitting </strong><strong>n values</strong>.</li><li>Very useful for <strong>one-time HTTP calls</strong> or when you just need the <strong>first few values</strong>.</li></ul><h4>🧪 Use Case Example</h4><ul><li>API call that should complete after a single response.</li><li>Limit a stream to first 5 items only.</li></ul><h4>🧪 Example:</h4><pre>interval(1000).pipe(<br>  take(3)<br>).subscribe(console.log); // emits 0, 1, 2 then completes</pre><p>I use take(1) with HTTP calls to automatically complete the observable and prevent memory leaks.</p><h3>takeUntil – Unsubscribe Automatically</h3><h4>🧪 What is it?</h4><ul><li>takeUntil(notifier$) keeps emitting values <strong>until another observable emits a value</strong>.</li><li>Typically used with ngOnDestroy() to <strong>auto-clean subscriptions</strong>.</li></ul><h4>🧪 Use Case Example</h4><ul><li>Automatically unsubscribe from valueChanges or interval when component is destroyed.</li></ul><h4>🧪 Example:</h4><pre>const destroy$ = new Subject&lt;void&gt;();<br><br>interval(1000).pipe(<br>  takeUntil(destroy$)<br>).subscribe(console.log);<br><br>// Later in ngOnDestroy<br>destroy$.next();<br>destroy$.complete();</pre><p>I use takeUntil(this.destroy$) pattern in Angular components to avoid memory leaks by unsubscribing when the component is destroyed.</p><h3>Combined Real-World Angular Example</h3><p>Let’s implement all three operators (tap, take, takeUntil) in an actual Angular component that:</p><ul><li>Fetches user profile</li><li>Logs the data (tap)</li><li>Takes only 1 response (take)</li><li>Auto-unsubscribes on destroy (takeUntil)</li></ul><p><strong>📦 user.service.ts</strong></p><pre>@Injectable({ providedIn: &#39;root&#39; })<br>export class UserService {<br>  constructor(private http: HttpClient) {}<br><br>  getUserProfile(): Observable&lt;any&gt; {<br>    return this.http.get(&#39;/api/user/profile&#39;); // One-time API call<br>  }<br>}</pre><p><strong>👤 user-profile.component.ts</strong></p><pre>@Component({<br>  selector: &#39;app-user-profile&#39;,<br>  template: `&lt;p *ngIf=&quot;user&quot;&gt;Welcome, {{ user.name }}&lt;/p&gt;`<br>})<br>export class UserProfileComponent implements OnInit, OnDestroy {<br>  user: any;<br>  private destroy$ = new Subject&lt;void&gt;();<br><br>  constructor(private userService: UserService) {}<br><br>  ngOnInit(): void {<br>    this.userService.getUserProfile()<br>      .pipe(<br>        tap(data =&gt; console.log(&#39;Fetched User Data:&#39;, data)), // tap for side effect<br>        take(1), // only take first value<br>        takeUntil(this.destroy$) // unsubscribe on destroy<br>      )<br>      .subscribe({<br>        next: userData =&gt; this.user = userData,<br>        error: err =&gt; console.error(&#39;Error fetching user:&#39;, err)<br>      });<br>  }<br><br>  ngOnDestroy(): void {<br>    this.destroy$.next();<br>    this.destroy$.complete();<br>  }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92a5e4eb8686" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RxJS distinctUntilChanged]]></title>
            <link>https://medium.com/@bbcpatra/rxjs-distinctuntilchanged-153995252981?source=rss-cb91ffefbf8------2</link>
            <guid isPermaLink="false">https://medium.com/p/153995252981</guid>
            <dc:creator><![CDATA[The Frontend Fuel]]></dc:creator>
            <pubDate>Sun, 06 Apr 2025 08:31:09 GMT</pubDate>
            <atom:updated>2025-04-06T08:31:35.491Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HXhUTS3C17BeV_LHzu4Rgw.png" /></figure><p><strong>distinctUntilChanged </strong>is used to prevent emitting duplicate consecutive values in a stream.</p><h4>✅ Example Use Case</h4><p>Let’s assume you have an input box and want to perform a search <strong>only when the input value changes (distinct)</strong>, and not on every key stroke with the same value.</p><h4>💡 Step-by-Step Implementation</h4><ol><li><strong>Angular Component HTML</strong></li></ol><pre>&lt;input type=&quot;text&quot; [formControl]=&quot;searchControl&quot; placeholder=&quot;Search here...&quot; /&gt;</pre><p><strong>2. Angular Component TypeScript</strong></p><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-search&#39;,<br>  templateUrl: &#39;./search.component.html&#39;<br>})<br>export class SearchComponent implements OnInit {<br>  searchControl = new FormControl(&#39;&#39;);<br><br>  ngOnInit(): void {<br>    this.searchControl.valueChanges<br>      .pipe(<br>        debounceTime(300), // wait for 300ms pause in events<br>        distinctUntilChanged() // only emit when value is different from previous<br>      )<br>      .subscribe(value =&gt; {<br>        console.log(&#39;Search term:&#39;, value);<br>        // You can call a search API here<br>      });<br>  }<br>}</pre><h4>🧠 What’s Happening Here?</h4><p>✅ valueChanges: Emits every time the input value changes.</p><p>✅ debounceTime(300): Waits for 300ms after the user stops typing.</p><p>✅ distinctUntilChanged(): Prevents emitting the same value consecutively.</p><h4>🍔 Analogy: Fast-Food Order Display</h4><p>Imagine a screen in a fast-food kitchen that shows the latest <strong>order</strong> to the chefs.</p><p><strong>Without </strong><strong>distinctUntilChanged</strong></p><p>Every time a customer sends <strong>any</strong> order — even if it’s the <strong>same as the previous one</strong>, it shows up on the screen</p><pre>Order: Burger 🍔 → Displayed<br>Order: Burger 🍔 (again) → Displayed again (unnecessarily)</pre><p><strong>With </strong><strong>distinctUntilChanged</strong></p><p>The system checks: <em>“Is this order the same as the last one?”</em> If yes, skip it!</p><pre>Order: Burger 🍔 → Displayed<br>Order: Burger 🍔 → Ignored (already cooking it!)<br>Order: Fries 🍟 → Displayed<br>Order: Fries 🍟 → Ignored</pre><p>This way, only <strong>new</strong> or <strong>changed</strong> inputs trigger actions — saving effort, time, and processing.</p><h3>Let’s build a complete example using</h3><p>⚙️ FormControl for capturing user input</p><p>⚙️ debounceTime to wait for user to stop typing</p><p>⚙️ distinctUntilChanged to ignore duplicate searches</p><p>⚙️ filter to ignore short/empty values</p><p>⚙️ switchMap to cancel previous requests and call an API only for the latest input</p><p>✅ Scenario: Real-Time Search (e.g., search users by name)</p><pre>&lt;input type=&quot;text&quot; [formControl]=&quot;searchControl&quot; placeholder=&quot;Search user...&quot; /&gt;<br>&lt;ul&gt;<br>  &lt;li *ngFor=&quot;let user of users&quot;&gt;{{ user.name }}&lt;/li&gt;<br>&lt;/ul&gt;</pre><p>⚙️ 2. <strong>Component TS</strong></p><pre>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { FormControl } from &#39;@angular/forms&#39;;<br>import { debounceTime, distinctUntilChanged, filter, switchMap } from &#39;rxjs/operators&#39;;<br>import { of } from &#39;rxjs&#39;;<br>import { UserService } from &#39;./user.service&#39;;<br><br>@Component({<br>  selector: &#39;app-user-search&#39;,<br>  templateUrl: &#39;./user-search.component.html&#39;<br>})<br>export class UserSearchComponent implements OnInit {<br>  searchControl = new FormControl(&#39;&#39;);<br>  users: any[] = [];<br><br>  constructor(private userService: UserService) {}<br><br>  ngOnInit(): void {<br>    this.searchControl.valueChanges.pipe(<br>      debounceTime(300),<br>      filter(value =&gt; value &amp;&amp; value.length &gt; 2), // only if 3+ characters<br>      distinctUntilChanged(),<br>      switchMap(query =&gt; this.userService.searchUsers(query)) // cancels old request<br>    ).subscribe(result =&gt; {<br>      this.users = result;<br>    });<br>  }<br>}</pre><p>🔌 3. <strong>User Service (Simulated API Call)</strong></p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { of } from &#39;rxjs&#39;;<br>import { delay } from &#39;rxjs/operators&#39;;<br><br>@Injectable({ providedIn: &#39;root&#39; })<br>export class UserService {<br>  private dummyUsers = [<br>    { name: &#39;Alice&#39; },<br>    { name: &#39;Bob&#39; },<br>    { name: &#39;Charlie&#39; },<br>    { name: &#39;David&#39; }<br>  ];<br><br>  searchUsers(query: string) {<br>    const filtered = this.dummyUsers.filter(user =&gt;<br>      user.name.toLowerCase().includes(query.toLowerCase())<br>    );<br>    return of(filtered).pipe(delay(500)); // simulate network delay<br>  }<br>}</pre><h3>🚀 Flow Summary:</h3><p>⚙️ User types → waits 300ms</p><p>⚙️ If input is 3+ characters and has changed → API call is made</p><p>⚙️ If the user types again quickly → previous request is canceled (thanks to switchMap)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=153995252981" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular error handling]]></title>
            <link>https://medium.com/@bbcpatra/angular-error-handling-4090294dab3f?source=rss-cb91ffefbf8------2</link>
            <guid isPermaLink="false">https://medium.com/p/4090294dab3f</guid>
            <category><![CDATA[rxjs-operators]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[rxjs-observables]]></category>
            <category><![CDATA[error-handling]]></category>
            <dc:creator><![CDATA[The Frontend Fuel]]></dc:creator>
            <pubDate>Sun, 06 Apr 2025 08:11:38 GMT</pubDate>
            <atom:updated>2025-04-06T08:11:38.563Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s_psmEksx1lsF8v1sY-VEQ.png" /></figure><p>Here’s how we can use throwError from RxJS in an Angular service or component — usually for error handling or simulating an error response in an Observable chain.</p><p>✅ Step-by-step Example: Using throwError in Angular</p><pre>import { throwError } from &#39;rxjs&#39;;<br>import { catchError } from &#39;rxjs/operators&#39;;</pre><p>✅ Scenario: HTTP call with error handling</p><p>Let’s say you have a service method that makes an HTTP call and you want to use throwError for error propagation.</p><pre>// student.service.ts<br><br>import { Injectable } from &#39;@angular/core&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;<br>import { catchError, throwError } from &#39;rxjs&#39;;<br><br>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class StudentService {<br><br>  private apiUrl = &#39;https://api.example.com/students&#39;;<br><br>  constructor(private http: HttpClient) {}<br><br>  getStudents() {<br>    return this.http.get(this.apiUrl).pipe(<br>      catchError(this.handleError)<br>  // catchError(() =&gt; throwError(() =&gt; new Error(&#39;Something went wrong while fetching students.&#39;)))<br>    );<br>  }<br><br>  private handleError(error: any) {<br>    // Custom logic or logging<br>    console.error(&#39;Error occurred:&#39;, error);<br><br>    // Return observable with error message<br>    return throwError(() =&gt; new Error(&#39;Something went wrong while fetching students.&#39;));<br>  }<br>}</pre><h4>🧪 Using It in Component</h4><pre>// student.component.ts<br><br>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { StudentService } from &#39;./student.service&#39;;<br><br>@Component({<br>  selector: &#39;app-student&#39;,<br>  template: &#39;&lt;div *ngIf=&quot;errorMsg&quot;&gt;{{ errorMsg }}&lt;/div&gt;&#39;<br>})<br>export class StudentComponent implements OnInit {<br>  errorMsg: string = &#39;&#39;;<br><br>  constructor(private studentService: StudentService) {}<br><br>  ngOnInit() {<br>    this.studentService.getStudents().subscribe({<br>      next: data =&gt; {<br>        console.log(&#39;Students:&#39;, data);<br>      },<br>      error: err =&gt; {<br>        this.errorMsg = err.message;<br>      }<br>    });<br>  }<br>}</pre><p>✅ Here’s How You Can Explain It in an Interview</p><p>In Angular, we use RxJS’s throwError to return an error Observable. If I want to simulate an error, for example during testing, I can directly return throwError(() =&gt; new Error(‘…’)). But in a real-world HTTP scenario, I use it inside catchError to gracefully handle errors after an API call fails.</p><p>✅ Example Interview Answer<br>Q: How do you handle errors in Angular services using RxJS?</p><p>A: I use catchError from RxJS to intercept and handle errors in HTTP calls. Inside catchError, I can use throwError to return a custom error Observable.<br><strong>For example</strong></p><pre>getStudents() {<br>  return this.http.get(this.apiUrl).pipe(<br>    catchError(() =&gt; throwError(() =&gt; new Error(&#39;Failed to fetch students.&#39;)))<br>  );<br>}</pre><p>This allows the component to subscribe and handle errors without breaking the stream.</p><h4>✅ Tips to Impress:</h4><ul><li>Show that you know <strong>the difference between simulating an error</strong> and <strong>handling a real error</strong>.</li><li>Mention that throwError(() =&gt; new Error(...)) is the <strong>recommended syntax</strong> as of RxJS 7+.</li><li>Bonus: If you mention that catchError returns an observable and <strong>should not break the stream</strong>, that’s great insig</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4090294dab3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced TypeScript part — 3]]></title>
            <link>https://medium.com/@bbcpatra/advanced-typescript-part-3-81ba5a8142b2?source=rss-cb91ffefbf8------2</link>
            <guid isPermaLink="false">https://medium.com/p/81ba5a8142b2</guid>
            <category><![CDATA[typeface]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[promises-in-javascript]]></category>
            <category><![CDATA[typescript-tutorial]]></category>
            <dc:creator><![CDATA[The Frontend Fuel]]></dc:creator>
            <pubDate>Fri, 04 Apr 2025 05:05:26 GMT</pubDate>
            <atom:updated>2025-04-04T05:05:26.108Z</atom:updated>
            <content:encoded><![CDATA[<h3>Advanced TypeScript part — 3</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HoaGX6Z6yfhzgQu74wmsQw.png" /></figure><h4>Object-Oriented Programming (OOP) in TypeScript</h4><p>TypeScript provides strong support for object-oriented programming concepts. Here’s a comprehensive overview of key OOP features in TypeScript:</p><h4>1. Classes &amp; Constructor</h4><p>A class in TypeScript is a blueprint for creating objects. The constructor method initializes object properties.</p><pre>class Person {<br>  name: string;<br>  age: number;<br><br>  constructor(name: string, age: number) {<br>    this.name = name;<br>    this.age = age;<br>  }<br><br>  greet() {<br>    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);<br>  }<br>}<br><br>const person1 = new Person(&quot;Sambhav&quot;, 25);<br>person1.greet();</pre><h4>2. Access Modifiers</h4><p>Access modifiers control the visibility of properties and methods:</p><ul><li><strong>public</strong>: Accessible everywhere (default).</li><li><strong>private</strong>: Accessible only within the class.</li><li><strong>protected</strong>: Accessible within the class and its subclasses.</li><li><strong>readonly</strong>: The property cannot be modified after initialization.</li></ul><pre>class Employee {<br>  public name: string;       // Can be accessed anywhere<br>  private salary: number;    // Can only be accessed within the class<br>  protected department: string;  // Can be accessed within the class and subclasses<br>  readonly id: number;       // Can only be assigned once<br><br>  constructor(name: string, salary: number, department: string, id: number) {<br>    this.name = name;<br>    this.salary = salary;<br>    this.department = department;<br>    this.id = id;<br>  }<br><br>  getSalary() {<br>    return this.salary;<br>  }<br>}<br><br>const emp = new Employee(&quot;John&quot;, 50000, &quot;IT&quot;, 101);<br>console.log(emp.name);  // ✅ Allowed<br>// console.log(emp.salary);  // ❌ Error: Property &#39;salary&#39; is private<br>console.log(emp.getSalary()); // ✅ Allowed<br>// emp.id = 102;  // ❌ Error: Cannot assign to &#39;id&#39; because it is a read-only property</pre><h4>3. Static Properties &amp; Methods</h4><p>Static members belong to the class itself, not instances.</p><pre>class MathUtil {<br>  static pi: number = 3.14;<br><br>  static calculateCircumference(radius: number): number {<br>    return 2 * this.pi * radius;<br>  }<br>}<br><br>console.log(MathUtil.pi);  // ✅ Allowed<br>console.log(MathUtil.calculateCircumference(5));  // ✅ Allowed</pre><h4>4. Inheritance (extends)</h4><p>A child class can inherit from a parent class using extends.</p><pre>class Animal {<br>    public name: string; // Fixed property name<br>    public color: string;<br><br>    constructor(name: string, color: string) {<br>        this.name = name;<br>        this.color = color;<br>    }<br>}<br><br>class Cat extends Animal {<br>    public age: number;<br><br>    constructor(name: string, color: string, age: number) {<br>        super(name, color); // Correctly calling parent constructor<br>        this.age = age;<br>    }<br><br>    getDetails() {<br>        console.log(this.name, this.age, this.color); // Fixed property access<br>    }<br>}<br><br>const cat = new Cat(&quot;MIKE&quot;, &quot;black&quot;, 12);<br>cat.getDetails(); // Output: MIKE 12 black</pre><h4>5. Getters &amp; Setters</h4><p>Getters (get) and setters (set) allow controlled access to properties.</p><pre>class BankAccount {<br>  private _balance: number = 0;<br><br>  get balance(): number {<br>    return this._balance;<br>  }<br><br>  set balance(amount: number) {<br>    if (amount &lt; 0) {<br>      console.log(&quot;Balance cannot be negative.&quot;);<br>    } else {<br>      this._balance = amount;<br>    }<br>  }<br>}<br><br>const account = new BankAccount();<br>account.balance = 1000;  // ✅ Setter is called<br>console.log(account.balance); // ✅ Getter is called, Output: 1000</pre><h4>6. Abstract Classes</h4><p>An <strong>abstract class</strong> in TypeScript is a blueprint for other classes. It cannot be instantiated directly and may contain <strong>abstract methods</strong> that must be implemented by derived classes.</p><p><strong>Key Points</strong></p><ul><li>Defined using the abstract keyword.</li><li>Can have both abstract and non-abstract methods.</li></ul><pre>abstract class Vehicle {<br>  abstract move(): void;  // Abstract method (must be implemented in derived classes)<br><br>  start() {<br>    console.log(&quot;Vehicle is starting...&quot;);<br>  }<br>}<br><br>class Car extends Vehicle {<br>  move() {<br>    console.log(&quot;Car is moving&quot;);<br>  }<br>}<br><br>const car = new Car();<br>car.start(); // Output: Vehicle is starting...<br>car.move();  // Output: Car is moving</pre><h4>7. Method Overriding</h4><p>A subclass can override a method from its superclass.</p><pre>class Parent {<br>  greet() {<br>    console.log(&quot;Hello from Parent&quot;);<br>  }<br>}<br><br>class Child extends Parent {<br>  greet() {<br>    console.log(&quot;Hello from Child&quot;);<br>  }<br>}<br><br>const obj = new Child();<br>obj.greet(); // Output: Hello from Child</pre><p>These OOP concepts help you write clean, modular, and reusable code in TypeScript. 😊</p><h4>Functions in TypeScript</h4><p>TypeScript provides powerful function features like <strong>function types, optional/default parameters, rest parameters, function overloading, and arrow functions with </strong><strong>this binding</strong>. Let’s go through each concept with examples.</p><h4>1. Function Types</h4><p>A function type defines the types of <strong>parameters</strong> and the <strong>return value</strong>.</p><pre>vfunction add(x: number, y: number): number {<br>  return x + y;<br>};<br><br>console.log(add(10, 20)); // Output: 30</pre><h4>How It Works?</h4><ul><li>The function type (a: number, b: number) =&gt; number means:</li><li>The function <strong>takes two numbers</strong> as parameters.</li><li>It <strong>returns a number</strong>.</li></ul><h4>2. Optional &amp; Default Parameters</h4><ul><li><strong>Optional Parameters (</strong><strong>param?: type)</strong>: The parameter can be <strong>omitted</strong>.</li><li><strong>Default Parameters (</strong><strong>param: type = defaultValue)</strong>: If omitted, it gets a <strong>default value</strong>.</li></ul><h4>Example:</h4><pre>function greet(name: string, message?: string, suffix: string = &quot;Welcome!&quot;) {<br>  console.log(`${message || &quot;Hello&quot;}, ${name}! ${suffix}`);<br>}<br><br>greet(&quot;Sambhav&quot;);                // Output: Hello, Sambhav! Welcome!<br>greet(&quot;Sambhav&quot;, &quot;Good morning&quot;); // Output: Good morning, Sambhav! Welcome!<br>greet(&quot;Sambhav&quot;, &quot;Hi&quot;, &quot;How are you?&quot;); // Output: Hi, Sambhav! How are you?</pre><h4>How It Works?</h4><ul><li>message?: string → This is an <strong>optional parameter</strong>.</li><li>suffix: string = &quot;Welcome!&quot; → If omitted, &quot;Welcome!&quot; is used as a <strong>default value</strong>.</li></ul><h4>3. Rest Parameters (...args)</h4><p>Rest parameters allow a function to accept <strong>multiple arguments</strong> as an array.</p><pre>function sum(...numbers: number[]): number {<br>  return numbers.reduce((acc, num) =&gt; acc + num, 0);<br>}<br><br>console.log(sum(1, 2, 3, 4, 5)); // Output: 15<br>console.log(sum(10, 20));        // Output: 30</pre><h4>How It Works?</h4><ul><li>...numbers: number[] means <strong>any number of parameters</strong> will be stored in an <strong>array</strong>.</li><li>reduce((acc, num) =&gt; acc + num, 0) sums up all elements.</li></ul><h4>4. Function Overloading</h4><p>Function overloading allows defining <strong>multiple function signatures</strong> with the same name but <strong>different parameter types</strong>.</p><pre>function displayInfo(info: string): void;<br>function displayInfo(info: number): void;<br>function displayInfo(info: string | number): void {<br>  if (typeof info === &quot;string&quot;) {<br>    console.log(`Name: ${info}`);<br>  } else {<br>    console.log(`Age: ${info}`);<br>  }<br>}<br><br>displayInfo(&quot;Sambhav&quot;); // Output: Name: Sambhav<br>displayInfo(25);        // Output: Age: 25</pre><h4>How It Works?</h4><ul><li><strong>First two lines define function overload signatures.</strong></li><li>The actual function <strong>handles both cases</strong> (string and number).</li><li>This ensures <strong>type safety</strong> while allowing multiple argument types.</li></ul><h4>5. Arrow Functions &amp; this Binding</h4><p>Arrow functions <strong>preserve the </strong><strong>this context</strong> of their surrounding scope.</p><h4>Problem with this in Regular Functions</h4><pre>class Person {<br>  name = &quot;Sambhav&quot;;<br><br>  greet() {<br>    setTimeout(function () {<br>      console.log(`Hello, ${this.name}`); // ❌ &#39;this&#39; is undefined here<br>    }, 1000);<br>  }<br>}<br><br>const p = new Person();<br>p.greet(); // Output: Hello, undefined</pre><p>The function inside setTimeout has its own this, so it <strong>loses the context of </strong><strong>Person</strong>.</p><h4>Solution: Use Arrow Function</h4><pre>class Person {<br>  name = &quot;Sambhav&quot;;<br><br>  greet() {<br>    setTimeout(() =&gt; {<br>      console.log(`Hello, ${this.name}`); // ✅ &#39;this&#39; refers to Person instance<br>    }, 1000);<br>  }<br>}<br><br>const p = new Person();<br>p.greet(); // Output: Hello, Sambhav</pre><h4>How Arrow Functions Fix this?</h4><ul><li>Arrow functions <strong>do not have their own </strong><strong>this</strong>.</li><li>They inherit this from the <strong>surrounding function</strong> (i.e., Person class in this case).</li></ul><h4>Modules &amp; Namespaces in TypeScript</h4><h4>1. ES Modules in TypeScript</h4><p>TypeScript supports <strong>ECMAScript Modules (ESM)</strong>, which use import and export for modular programming. This approach is widely used in modern TypeScript.</p><p>Exporting inv TypeScript (Named &amp; Default Export)</p><pre>// mathUtils.ts<br>export const add = (a: number, b: number) =&gt; a + b;<br>export const subtract = (a: number, b: number) =&gt; a - b;<br><br>// Default export<br>export default function multiply(a: number, b: number) {<br>  return a * b;<br>}</pre><p>Importing in TypeScript</p><pre>// main.ts<br>import { add, subtract } from &quot;./mathUtils&quot;; // Named import<br>import multiply from &quot;./mathUtils&quot;; // Default import<br><br>console.log(add(5, 3)); // 8<br>console.log(subtract(10, 4)); // 6<br>console.log(multiply(4, 3)); // 12</pre><p>The difference between import {} (named import) and import without {} (default import)</p><h4>1. Named Imports (import {})</h4><p>Named imports are used when a module exports multiple values using export (not export default).</p><ul><li><strong>Uses </strong><strong>{}</strong> to specify the exact exports needed.</li><li><strong>Allows multiple imports from the same module.</strong></li><li><strong>Cannot rename imports unless using </strong><strong>as (e.g., </strong><strong>import { add as sum } from &quot;./mathUtils&quot;;).</strong></li></ul><pre>// mathUtils.ts<br>export const add = (a: number, b: number) =&gt; a + b;<br>export const subtract = (a: number, b: number) =&gt; a - b;<br><br><br>// main.ts<br>import { add, subtract } from &quot;./mathUtils&quot;; // Named import<br>console.log(add(5, 3)); // 8<br>console.log(subtract(10, 4)); // 6</pre><h4>Default Import (import without {})</h4><p>A <strong>default export</strong> allows importing a module without using {}.</p><p><strong>Example: Default Export &amp; Import</strong></p><pre>// mathUtils.ts<br>export default function multiply(a: number, b: number) {<br>  return a * b;<br>}<br><br>// main.ts<br>import multiply from &quot;./mathUtils&quot;; // Default import (no `{}` needed)<br>console.log(multiply(4, 3)); // 12</pre><ul><li><strong>No </strong><strong>{} needed</strong> for default imports.</li><li><strong>Each module can have only one default export.</strong></li></ul><h4>When to Use What?</h4><ul><li><strong>Use named imports</strong> when a module exports multiple things.</li><li><strong>Use default imports</strong> when a module exports a single main function, class, or object.</li></ul><h3>Basic Types</h3><ul><li>string, number, boolean, null, undefined</li><li>void, any, unknown, never</li><li>Type inference &amp; Type annotations</li></ul><h3>Basic Types in TypeScript</h3><p>TypeScript provides static typing for JavaScript, allowing you to define variables with specific types. Let’s go through the core types and additional TypeScript-specific types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h8GBRLjuc6_3Duzgxr8MIg.png" /></figure><pre>let message: string = &quot;Hello, TypeScript!&quot;;<br>let age: number = 25;<br>let isStudent: boolean = true;<br>let emptyValue: null = null;<br>let notAssigned: undefined = undefined;</pre><h4>Complex Types</h4><p>These are different complex types in TypeScript. Here’s a quick breakdown:</p><h4>1. Arrays</h4><ul><li>You can define arrays in two ways:</li></ul><pre>let numbers: number[] = [1, 2, 3, 4, 5];<br>let names: Array&lt;string&gt; = [&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;];</pre><h4>2. Enums</h4><ul><li>Enums define named constants.</li></ul><pre>enum Status {<br>    Active,<br>    Inactive,<br>    Pending<br>}<br><br>let currentStatus: Status = Status.Active;</pre><h4>3. Literal Types</h4><ul><li>You can define a type that only allows specific values.</li></ul><pre>let responseStatus: &quot;success&quot; | &quot;error&quot;;<br>responseStatus = &quot;success&quot;; // ✅ Valid<br>responseStatus = &quot;failure&quot;; // ❌ Error</pre><h4>4. Interfaces</h4><ul><li>Interfaces define the structure of an object.</li></ul><h4>Key Points:</h4><ul><li>Defines a contract for object structure.</li><li>Only contains method and property declarations, no implementation.</li><li>Supports <strong>optional properties</strong> (?), <strong>readonly properties</strong>, and <strong>function signatures</strong>.</li><li>Used for <strong>type safety</strong> and <strong>code reusability</strong>.</li></ul><pre>interface Person {<br>  name: string;<br>  age: number;<br>  greet(): string;<br>}<br><br>const user: Person = {<br>  name: &quot;John&quot;,<br>  age: 25,<br>  greet() {<br>    return `Hello, my name is ${this.name}`;<br>  },<br>};<br><br>console.log(user.greet()); // Output: Hello, my name is John</pre><pre>class Employee implements Person {<br>  constructor(public name: string, public age: number) {}<br>  greet() {<br>    return `Hi, I&#39;m ${this.name}`;<br>  }<br>}</pre><h4>Why Use Interfaces?</h4><p>✅ Ensures consistency<br> ✅ Improves maintainability<br> ✅ Supports <strong>Duck Typing</strong> (structural typing)</p><h4>5. Tuples</h4><ul><li>A tuple is a fixed-length array with specific types at each position.</li></ul><pre>let person: [string, number] = [&quot;John&quot;, 30];</pre><h3>Decorators in Angular and TypeScript</h3><p>Decorators are a special kind of declaration in TypeScript that allow you to attach metadata to classes, methods, properties, and parameters to modify their behavior at runtime. They are extensively used in <strong>Angular</strong> for defining components, services, directives, etc.</p><h3>1. Class Decorators</h3><p>These are used to define metadata for classes.</p><ul><li>@Component() – Defines an Angular component.</li><li>@Directive() – Defines a directive.</li><li>@Injectable() – Marks a class as available for dependency injection.</li><li>@NgModule() – Defines an Angular module.</li></ul><h4>2. Method Decorators</h4><p>These are used to modify the behavior of a class method.</p><ul><li>@HostListener(eventName) – Listens to events on the host element.</li><li>@Debounce(time) – Custom decorator to delay method execution.</li></ul><h4>3. Property Decorators</h4><p>These are used to decorate properties inside a class.</p><ul><li>@Input() – Marks a property as an input binding.</li><li>@Output() – Marks a property as an output event emitter.</li></ul><h4>4. Parameter Decorators</h4><p>These are used to decorate parameters inside a constructor.</p><ul><li>@Inject(token) – Used for dependency injection.</li><li>@Optional() – Marks a parameter as optional in DI.</li><li>@Self(), @SkipSelf(), @Host() – Used in Angular DI.</li></ul><h4>Conclusion</h4><p>Decorators are powerful in Angular and TypeScript for enhancing code readability, modularity, and functionality by adding metadata and modifying behaviors dynamically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*VN555RxBbwSF5JpQoxLofw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81ba5a8142b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>