<?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 Rahul Shaw on Medium]]></title>
        <description><![CDATA[Stories by Rahul Shaw on Medium]]></description>
        <link>https://medium.com/@therahulkshaw?source=rss-5a88aa06f398------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*G90rADEf2IZOOAmz</url>
            <title>Stories by Rahul Shaw on Medium</title>
            <link>https://medium.com/@therahulkshaw?source=rss-5a88aa06f398------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 23:15:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@therahulkshaw/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 21 Guards — A GoTo Guide You Wish You Had]]></title>
            <link>https://medium.com/@therahulkshaw/angular-21-guards-a-goto-guide-you-wish-you-had-da5f85e98ac0?source=rss-5a88aa06f398------2</link>
            <guid isPermaLink="false">https://medium.com/p/da5f85e98ac0</guid>
            <category><![CDATA[angular-guards]]></category>
            <category><![CDATA[angular-14-guards]]></category>
            <category><![CDATA[angular-21-guards]]></category>
            <dc:creator><![CDATA[Rahul Shaw]]></dc:creator>
            <pubDate>Sun, 30 Nov 2025 16:11:32 GMT</pubDate>
            <atom:updated>2025-11-30T16:11:32.870Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*maq7FA5iDIDrtTXlS7pq4Q.png" /><figcaption>Angular Guards</figcaption></figure><h3>Angular 21 Guards — A GoTo Guide You Wish You Had</h3><p>If you have ever built an Angular app, you probably asked yourself at some point:</p><p><em>“How do I stop users from opening pages they’re not supposed to see?”</em></p><p>Maybe a user is not logged in.<br>Maybe their subscription expired.<br>Maybe you want to run a quick check before letting them inside a route.</p><p>For all these situations, Angular uses something powerful called <strong>guards</strong>.</p><h3>What Are Guards?</h3><p>Think of guards like <strong>security checkpoints</strong> in your app.</p><p>When a user tries to open a page (route), a guard decides:</p><ul><li>Allow them in</li><li>Block them</li><li>Redirect them</li></ul><p>Just like a security guard outside a building checks ID cards, Angular guards check your app’s conditions before navigation.</p><h3>Why Do We Use Guards?</h3><p><em>We use guards to </em><strong><em>control who can access which page</em></strong><em> or </em><strong><em>whether the user can leave a page</em></strong><em>.</em></p><ul><li>Only logged-in users can open the dashboard</li><li>Only admins can open the admin panel</li><li>Users must complete payment before accessing premium pages</li><li>Prevent losing unsaved data when leaving a form page</li></ul><p>Guards make your app safer, cleaner, and more consistent.</p><h3>When Should You Use Guards?</h3><p><em>Use a guard whenever you want to:</em></p><ul><li>Protect a route before entry</li><li>Protect child routes under a parent</li><li>Prevent navigation away under certain conditions (like unsaved forms)</li><li>Dynamically decide whether a route configuration should match (for A/B features, feature flags, or module-level control)</li></ul><p>Guards are perfect for login systems, onboarding flows, admin panels, unsaved-form warnings, feature toggles, and more.</p><h3>How to Create Angular Guards.</h3><p>To create a guard, using Angular CLI:</p><pre>ng generate guard &lt;guard-name&gt;</pre><h3>Where Do We Use Guards?</h3><p>You apply guards <strong>inside your route configuration</strong>, usually in the routes (or Routes) array.</p><pre>{<br>  path: &#39;dashboard&#39;,<br>  canActivate: [authGuard],<br>  loadComponent: () =&gt; import(&#39;./dashboard&#39;).then(c =&gt; c.Dashboard)<br>}</pre><p>the guard decides if this route should open or not.</p><h3>How Guards Worked Before version 15</h3><p><em>(Class-based Style was used till version 14)</em></p><p>Earlier versions of Angular used <strong>class-based guards</strong> (interfaces like CanActivate, CanDeactivate, etc.).</p><pre>@Injectable({ providedIn: &#39;root&#39; })<br>export class AuthGuard implements CanActivate {<br>  constructor(private auth: AuthService, private router: Router) {}<br><br>  canActivate(): boolean {<br>    if (!this.auth.isLoggedIn()) {<br>      this.router.navigate([&#39;/&#39;]);<br>      return false;<br>    }<br>    return true;<br>  }<br>}</pre><p>Similar class-based code existed for other guards like CanDeactivate, CanActivateChild, CanMatch/CanLoad, etc. The pattern involves creating a class, implementing the appropriate interface, injecting services via constructor, and returning true/false (or other types) from the guard method.</p><p>This worked — but it had drawbacks:</p><ul><li>Too much boilerplate</li><li>Need to create classes for every guard</li><li>Less intuitive and more verbose</li></ul><h3>How Guards Work in Angular after version 14</h3><p><em>(Function-Based Style)</em></p><p>Angular now uses <strong>function-based guards</strong> — no classes, no interface-implementing boilerplate, just simple functions using inject() when dependencies are needed.</p><p>All four guards can now be implemented as standalone functions:</p><ul><li><em>CanActivateFn</em></li><li><em>CanActivateChildFn</em></li><li><em>CanDeactivateFn&lt;T&gt;</em></li><li><em>CanMatchFn</em></li></ul><p><strong>1.CanActivate</strong> — Decide if route can be activated<br><em>Use this to protect the route based on certain conditions.</em></p><pre>import { CanActivateFn, Router } from &#39;@angular/router&#39;;<br>import { inject } from &#39;@angular/core&#39;;<br>import { Auth } from &#39;./auth&#39;;<br><br>export const authGuard: CanActivateFn = (route, state) =&gt; {<br>  const auth = inject(Auth);<br>  const router = inject(Router);<br><br>  if (!auth.isLoggedIn()) {<br>    router.navigate([&#39;/login&#39;]); <br>    return false;<br>  }<br>  return true;<br>};</pre><pre>{ <br>  path: &#39;dashboard&#39;, <br>  canActivate: [authGuard], <br>  loadComponent: () =&gt; import(&#39;./dashboard&#39;).then(c =&gt; c.Dashboard) <br>}</pre><p>This guard checks if the user is logged in. If not, they are redirected to the login page.</p><p><strong>2.CanActivateChild</strong> — Guard for child routes <br><em>Use this when you have nested/child routes and want to protect all of them under a parent.</em></p><pre>import { CanActivateChildFn } from &#39;@angular/router&#39;;<br>import { inject } from &#39;@angular/core&#39;;<br>import { Auth } from &#39;./auth&#39;;<br><br>export const adminChildGuard: CanActivateChildFn = (childRoute, state) =&gt; {<br>  const auth = inject(Auth);<br>  return auth.userRole === &#39;admin&#39;;<br>};</pre><pre>{<br>  path: &#39;admin&#39;,<br>  canActivateChild: [adminChildGuard],<br>  children: [<br>    { path: &#39;users&#39;, loadComponent: () =&gt; import(&#39;./users&#39;).then(m =&gt; m.Users) },<br>    { path: &#39;settings&#39;, loadComponent: () =&gt; import(&#39;./settings&#39;).then(m =&gt; m.Settings) }<br>  ]<br>}</pre><p>All child route<strong> </strong>under /admin will be protected by the same guard.</p><p><strong>3.CanDeactivate</strong> — Decide if you can leave a route (navigate away)<br><em>Useful to prevent losing unsaved data (like leaving a form page without saving).</em></p><pre>import { CanDeactivateFn, Router } from &#39;@angular/router&#39;;<br>import { inject } from &#39;@angular/core&#39;;<br>import type { UserForm } from &#39;./user-form&#39;;<br><br>export const unsavedChangesGuard: CanDeactivateFn&lt;UserForm&gt; = (<br>  component,<br>  currentRoute,<br>  currentState,<br>  nextState<br>) =&gt; {<br>  if (component.hasUnsavedChanges()) {<br>    return confirm(&#39;You have unsaved changes. Do you really want to leave?&#39;);<br>  }<br>  return true;<br>};</pre><pre>{ <br>  path: &#39;edit-profile&#39;, <br>  canDeactivate: [unsavedChangesGuard],<br>  loadComponent: () =&gt; import(&#39;./userForm&#39;).then(m =&gt; m.UserForm),<br>}</pre><p>When user tries to leave this route, the guard runs — and asks for confirmation if there are unsaved changes.</p><p><strong>4.CanMatch</strong> — Decide if a route should match / load at all<br><em>This is useful for feature toggles, conditional route loading, role-based route availability, etc.</em></p><pre>import { CanMatchFn } from &#39;@angular/router&#39;;<br>import { inject } from &#39;@angular/core&#39;;<br>import { Feature } from &#39;./feature&#39;;<br><br>export const featureToggleGuard: CanMatchFn = (route, segments) =&gt; {<br>  const feature = inject(Feature);<br>  // Suppose we enable new dashboard only if feature flag is true<br>  return feature.isEnabled(&#39;newDashboard&#39;);<br>};</pre><pre>{ <br>  path: &#39;new-dashboard&#39;, <br>  canMatch: [featureToggleGuard], <br>  loadComponent: () =&gt; import(&#39;./new-dashboard&#39;).then(c =&gt; c.NewDashboard) <br>},<br>{ <br>  path: &#39;dashboard&#39;, <br>  loadComponent: () =&gt; import(&#39;./dashboard&#39;).then(c =&gt; c.Dashboard) <br>}</pre><p>If featureToggleGuard returns true, /new-dashboard route will match; otherwise router will skip it and maybe match fallback routes.</p><h3>Real-World Use Cases — When to Use Which Guard</h3><ul><li><strong>CanActivate</strong>: protect pages like dashboard, user profile — ensure user is logged in or has correct role</li><li><strong>CanActivateChild</strong>: protect an entire section of nested routes — e.g. admin panel with many child pages</li><li><strong>CanDeactivate</strong>: warn user when they try to leave a form page without saving changes</li><li><strong>CanMatch</strong>: enable/disable certain routes based on feature flags, user roles, subscription status or A/B testing</li></ul><p>Angular with latest release made guards <strong>lightweight</strong>, <strong>modern</strong>, and <strong>beginner-friendly</strong>. No more long classes. No more confusion. Just clean functions.</p><p>If you’re building apps that need login checks, admin restrictions, unsaved-form warnings, or feature-based route loading — guards will quickly become your best friends.</p><p>The new function-based style is not only easier — it also feels more “JavaScript-native” and matches the direction Angular is moving toward.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da5f85e98ac0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modern Angular Animations (Say Goodbye to the Old Way!)]]></title>
            <link>https://medium.com/@therahulkshaw/modern-angular-animations-say-goodbye-to-the-old-way-b14aa4673fea?source=rss-5a88aa06f398------2</link>
            <guid isPermaLink="false">https://medium.com/p/b14aa4673fea</guid>
            <category><![CDATA[angular-animations]]></category>
            <dc:creator><![CDATA[Rahul Shaw]]></dc:creator>
            <pubDate>Sat, 22 Nov 2025 17:12:25 GMT</pubDate>
            <atom:updated>2025-11-22T17:12:25.613Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*URgm6t7oqKKFCxlvaurTFA.png" /></figure><p>Have you ever clicked a button and — BOOM! — a new element appears out of nowhere?<br>No fade. No slide. No smoothness.<br>Just a <em>jump</em>.</p><p>It feels a bit like your app hit a speed breaker it didn’t see coming.</p><p>As developers, our job is not only to make apps work…<br>but also to make them <em>feel nice</em>.<br>Smooth animations do exactly that — they make your UI feel alive, friendly, and modern.</p><p>For years, Angular had its own animation system inside the @angular/animations package. It was powerful, but also heavy, complex, and honestly… a little intimidating for beginners.</p><p>But everything changed with Angular 21.</p><p>Angular is now leaning into <strong>native browser animations</strong>, giving us a simpler, faster, cleaner way to animate our apps. And yes — the old animation package is officially deprecated!</p><p>Let’s explore what animations are, how Angular used to handle them, and how Angular 21 makes it way easier.</p><h3>What Are Angular Animations?</h3><p>Animations are just slow, gradual changes on the screen.</p><p>Instead of an element suddenly appearing, we can make it <strong>fade in</strong>.<br>Instead of disappearing instantly, it can <strong>slide out</strong>.<br>Instead of jumping into place, it can <strong>move smoothly</strong>.</p><p>To understand the old system, imagine a theater play:</p><ul><li><strong>Triggers</strong> → The director’s signal (“Start the animation now!”)</li><li><strong>States</strong> → The different positions an element can be in (open/closed, shown/hidden)</li><li><strong>Transitions</strong> → How you move between states (fade, slide, shrink, etc.)</li></ul><p>Animations help by:</p><ul><li>Making the UI feel smoother</li><li>Guiding the user’s eye</li><li>Showing instant feedback</li><li>Giving modern vibes to your app</li></ul><h3>Why Even Use Animations?</h3><p>Here’s the short answer: <strong>Better experience = happier users</strong></p><p>But here’s the long answer:</p><ul><li><strong>Smooth transitions</strong> feel natural</li><li><strong>Animations grab attention</strong> where needed</li><li><strong>Native CSS animations</strong> (Angular 21) use the GPU = faster</li><li>They make your app feel premium</li></ul><p>Modern users expect nice animations. Flat, jumpy UIs feel outdated.</p><h3><strong>How It Used to Work (The Legacy Angular Way)</strong></h3><pre>//in module base application<br>import { BrowserAnimationsModule } from &#39;@angular/platform-browser/animations&#39;;<br><br>@NgModule({<br>  declarations: [<br>    AppComponent,<br>    // ... other components<br>  ],<br>  imports: [<br>    BrowserAnimationsModule // Add this to the imports array<br>  ],<br>  providers: [],<br>  bootstrap: [AppComponent]<br>})<br>export class AppModule { }<br><br>                                  OR<br><br>//in standalone base application<br><br>import { provideAnimations } from &#39;@angular/platform-browser/animations&#39;;<br><br>export const appConfig: ApplicationConfig = {<br>  providers: [<br>    provideAnimations()<br>  ]<br>};</pre><pre>import { Component } from &#39;@angular/core&#39;;<br>import {<br>  trigger,<br>  transition,<br>  style,<br>  animate<br>} from &#39;@angular/animations&#39;;<br><br>@Component({<br>  selector: &#39;app-legacy-animation&#39;,<br>  template: `<br>    &lt;div [@fadeInOut]=&quot;isOpen ? &#39;visible&#39; : &#39;hidden&#39;&quot;&gt;<br>      I am using the OLD Angular animation system — but with fade-in &amp; fade-out! ✨<br>    &lt;/div&gt;<br><br>    &lt;button (click)=&quot;toggle()&quot;&gt;Toggle&lt;/button&gt;<br>  `,<br>  animations: [<br>    trigger(&#39;fadeInOut&#39;, [<br><br>      // Fade In<br>      transition(&#39;hidden =&gt; visible&#39;, [<br>        style({<br>          opacity: 0,<br>          transform: &#39;translateY(10px)&#39;<br>        }),<br>        animate(&#39;400ms ease&#39;, style({<br>          opacity: 1,<br>          transform: &#39;translateY(0)&#39;<br>        }))<br>      ]),<br><br>      // Fade Out<br>      transition(&#39;visible =&gt; hidden&#39;, [<br>        style({<br>          opacity: 1,<br>          transform: &#39;translateY(0)&#39;<br>        }),<br>        animate(&#39;400ms ease&#39;, style({<br>          opacity: 0,<br>          transform: &#39;translateY(-10px)&#39;<br>        }))<br>      ])<br>    ])<br>  ]<br>})<br>export class LegacyAnimationComponent {<br>  isOpen = false;<br><br>  toggle() {<br>    this.isOpen = !this.isOpen;<br>  }<br>}</pre><p>This system was:</p><ul><li>Powerful</li><li>But heavy</li><li>And required learning special syntax</li><li>And increased your bundle size</li></ul><p>For simple fade/slide animations, this was overkill.</p><h3>The Angular 21+ Way: Simpler, Faster, Native</h3><p>Angular 21 finally says: <em>“Let the browser handle animations. CSS is powerful enough.”</em></p><p>And they’re right.</p><p>Modern Angular now uses <strong>native CSS animations</strong> + <strong>two simple template helpers</strong>:</p><h4><strong>animate.enter, animate.leave</strong></h4><p>These helpers add specific CSS classes at the exact moment an element enters or leaves the DOM.</p><ul><li>No more modules.</li><li>No more triggers.</li><li>No more Domain Specific Language (DSL).</li></ul><p>Just <strong>pure CSS</strong>.</p><h3>Why this is amazing:</h3><ul><li><strong>No large animation package</strong> → smaller bundles</li><li><strong>Better performance</strong> → GPU-accelerated animations</li><li><strong>Use skills you already know</strong> → CSS</li><li><strong>Cleaner code</strong> → no animation clutter in TypeScript</li><li><strong>Works great with libraries</strong> → GSAP, Anime.js, etc.</li></ul><pre>import { Component } from &#39;@angular/core&#39;;<br><br>@Component({<br>  standalone: true,<br>  selector: &#39;app-modern-animation&#39;,<br>  template: `<br>    @if (isVisible) {<br>      &lt;div animate.enter=&quot;fade-in&quot; animate.leave=&quot;fade-out&quot;&gt;<br>        I am using the NEW Angular 21+ animation style! ✨<br>      &lt;/div&gt;<br>    }<br><br>    &lt;button (click)=&quot;toggle()&quot;&gt;Toggle&lt;/button&gt;<br>  `,<br>  styles: `<br>    /* Fade In */<br>    .fade-in {<br>      opacity: 0;<br>      transform: translateY(10px);<br>      transition: opacity 0.4s ease, transform 0.4s ease;<br>    }<br><br>    /* Final state applied immediately */<br>    div {<br>      opacity: 1;<br>      transform: translateY(0);<br>    }<br><br>    /* Fade Out */<br>    .fade-out {<br>      opacity: 1;<br>      transform: translateY(0);<br>      transition: opacity 0.4s ease, transform 0.4s ease;<br>    }<br><br>    .fade-out.leave-active {<br>      opacity: 0;<br>      transform: translateY(-10px);<br>    }<br>  `<br>})<br>export class ModernAnimationComponent {<br>  isVisible = false;<br><br>  toggle() {<br>    this.isVisible = !this.isVisible;<br>  }<br>}</pre><h3>What’s happening here?</h3><ul><li>When the element appears → Angular adds fade-in ↠ CSS handles the effect</li><li>When the element disappears → Angular adds fade-out ↠ waits for animation to finish</li><li>No TS animation code</li><li>No extra modules</li><li>Pure CSS magic</li></ul><p>This is simpler, faster, and much more developer-friendly.</p><h3>Why This Matters (Especially for Beginners)</h3><p>Angular animations used to feel scary:</p><ul><li>Too many functions</li><li>Too much TypeScript</li><li>Too heavy for simple use cases</li><li>Too much friction for beginners</li></ul><p>Now, with Angular 21:</p><p>You animate like you would in plain HTML + CSS</p><ul><li>You don’t need a special module</li><li>You don’t learn a new syntax</li><li>You write cleaner components</li><li>Your app gets faster for free</li></ul><p>This is Angular becoming <strong>lighter</strong>, <strong>modern</strong>, and <strong>developer-friendly</strong>.</p><h3>Conclusion: Ready to Animate Your Angular World?</h3><p>Angular 21 has made animations <strong>simple again</strong>.</p><p>By embracing the browser (CSS + Web Animations API), Angular gives you:</p><ul><li>Smooth, GPU-powered animations</li><li>Smaller bundle sizes</li><li>Cleaner and easier code</li><li>A more modern development experience</li></ul><p>If you’ve avoided Angular animations in the past because they felt too complex, now is the perfect time to jump in.</p><ul><li>No special modules.</li><li>No complicated triggers.</li><li>Just pure CSS and simple, powerful helpers:<br> <strong>animate.enter</strong> and <strong>animate.leave</strong>.</li></ul><p>Your UI will feel more alive — and your users will feel the difference.<br>So go ahead… give your Angular app the smooth moves it deserves!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b14aa4673fea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Magic of Signals in Angular 20+ — The Future of Reactive Simplicity]]></title>
            <link>https://medium.com/@therahulkshaw/the-magic-of-signals-in-angular-20-the-future-of-reactive-simplicity-abc01471cca0?source=rss-5a88aa06f398------2</link>
            <guid isPermaLink="false">https://medium.com/p/abc01471cca0</guid>
            <dc:creator><![CDATA[Rahul Shaw]]></dc:creator>
            <pubDate>Wed, 29 Oct 2025 20:30:16 GMT</pubDate>
            <atom:updated>2025-10-29T20:30:16.193Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GmSyvXPSWC38l-kKOj6mNQ.png" /><figcaption>The Future of Reactivity</figcaption></figure><h3>The Magic of Signals in Angular 20+ — The Future of Reactive Simplicity</h3><p>If you’ve been building Angular apps for a while, you’ve probably heard the buzz about “Signals”. Maybe it sounds like another one of those complex, technical terms that require a whole new learning curve. I promise you, it’s not. It’s actually a massive step towards making Angular simpler, more intuitive, and way more performant.</p><p>We’ll break down what Signals are, why they were introduced, and how they’ll change the way you write code for the better.</p><p>We’ll use one running example — a <strong>User Dashboard</strong> that:</p><ol><li><em>fetches users from an API,</em></li><li><em>shows a loading state,</em></li><li><em>allows adding/removing users, and</em></li><li><em>demonstrates child → parent events via output signals.</em></li></ol><h3>Before Signals: The Old Way of Doing Things</h3><p>To understand why Signals are such a big deal, we need to talk about what life was like without them. Angular has always been great, but its reactivity (the way it automatically updates the UI when data changes) had a few wrinkles.</p><ol><li><strong>The “Zone.js” Problem</strong>: Angular used a library called Zone.js. It was a clever piece of magic that basically monitored almost every asynchronous action happening in your app — like a button click, an HTTP request, or a timer. When one of these events happened, Zone.js would tell Angular to run a “change detection” cycle. Angular would then have to check <em>every single component</em> in your app to see if anything had changed.</li></ol><ul><li><strong>The Analogy</strong>: Imagine you have a big house with 100 rooms. When someone turns on a light in just one room, you have to run through all 100 rooms to see if any of the other light switches moved. It’s exhaustive and, in a large, complex app, it can become a performance bottleneck.</li></ul><p>2.<strong> The RxJS Complexity</strong>: For more complex, async data, we relied heavily on RxJS and Observables. RxJS is an incredibly powerful library, but let’s be honest: it has a steep learning curve. For simple things, like a button that toggles a boolean, it felt like using a sledgehammer to crack a nut. You had to remember to subscribe, manage subscriptions to avoid memory leaks, and learn a whole new set of operators.</p><p>These weren’t bad systems, but they weren’t perfect. They could lead to inefficient performance and a lot of extra mental overhead, especially for beginners.</p><h4>user.service.ts</h4><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;<br>import { BehaviorSubject, Observable } from &#39;rxjs&#39;;<br><br>@Injectable({ providedIn: &#39;root&#39; })<br>export class UserService {<br>  private users$ = new BehaviorSubject&lt;any[]&gt;([]);<br><br>  constructor(private http: HttpClient) {}<br><br>  getUsers$(): Observable&lt;any[]&gt; {<br>    return this.users$.asObservable();<br>  }<br><br>  fetchUsers() {<br>    this.http.get&lt;any[]&gt;(&#39;https://jsonplaceholder.typicode.com/users&#39;)<br>      .subscribe(users =&gt; this.users$.next(users));<br>  }<br>}</pre><h4>user-dashboard.component.ts</h4><pre>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { UserService } from &#39;./user.service&#39;;<br><br>@Component({<br>  selector: &#39;app-user-dashboard&#39;,<br>  templateUrl: &#39;./user-dashboard.component.html&#39;<br>})<br>export class UserDashboardComponent implements OnInit {<br>  constructor(public userService: UserService) {}<br><br>  ngOnInit() {<br>    this.userService.fetchUsers();<br>  }<br><br>  refresh() {<br>    this.userService.fetchUsers();<br>  }<br>}</pre><h4>user-dashboard.component.html</h4><pre>&lt;div *ngIf=&quot;(userService.getUsers$() | async) as users; else loading&quot;&gt;<br>  &lt;ul&gt;<br>    &lt;li *ngFor=&quot;let user of users; trackBy: trackById&quot;&gt;<br>      {{ user.name }}<br>    &lt;/li&gt;<br>  &lt;/ul&gt;<br>  &lt;button (click)=&quot;refresh()&quot;&gt;Refresh&lt;/button&gt;<br>&lt;/div&gt;<br><br>&lt;ng-template #loading&gt;<br>  &lt;p&gt;Loading users...&lt;/p&gt;<br>&lt;/ng-template&gt;</pre><p><strong>Problems with this approach</strong></p><ul><li>BehaviorSubject for simple state; more boilerplate.</li><li>async pipe hides subscription logic but you still have a stream layer just to store a value.</li><li>Component templates rely on *ngIf and ng-template which is fine — but mixing Observables + state + UI sometimes becomes hard to reason about.</li></ul><h3>When, Why, and What Are Signals?</h3><p>Let’s talk about when and why you should use Signals — and what exactly they are.</p><h4>When do you reach for Signals?</h4><p>You’ll use Signals when:</p><ul><li>You have <strong>local or shared state</strong> that your UI depends on.</li><li>You want <strong>simpler component logic</strong> with automatic reactivity.</li><li>You want <strong>derived values</strong> (like totals or filters) that update automatically without extra wiring.</li></ul><h4>Why Signals?</h4><ul><li><strong>Less boilerplate:</strong> no need for manual subscriptions or async pipes for simple state.</li><li><strong>Faster updates:</strong> Angular only updates what depends on the changed signal.</li><li><strong>Easier to reason about:</strong> state looks and feels like a variable (count()) but reacts automatically when it changes.</li></ul><p>Before Signals, Angular used Zone.js and Observables to detect changes and manage async data. It worked — but it was like using a sledgehammer for a simple nail. With Signals, you get reactivity that’s much more direct and predictable.</p><h4>What Are Signals?</h4><p>Signals are Angular’s <strong>modern, fine-grained reactivity system</strong>.<br> Think of a Signal as a small wrapper around a value — it tells Angular when that value changes.</p><p>When a signal changes, Angular knows <em>exactly</em> which parts of the UI depend on it and updates only those parts.</p><p>It’s like having a <strong>smart home system</strong> — when a motion sensor detects movement in one room, only the lights in that room turn on, not the whole house. That’s what Signals do for your app’s performance.</p><h3>What Problems Do Signals Solve?</h3><ul><li><strong>Fine-grained reactivity:</strong> Only the affected components re-render.</li><li><strong>Reduced complexity:</strong> No more RxJS for simple local state or view updates.</li><li><strong>The path to Zoneless Angular:</strong> Signals make it possible to drop Zone.js entirely in the future, improving speed and control.</li></ul><h3>Types of Signals and How do we use them</h3><p>Let’s explore the 5 building blocks of Angular Signals.</p><p>1.signal() — writable signal (state) <br> (<em>think of </em><strong><em>useState()</em></strong><em> in react world)</em></p><p>Holds and updates a value.</p><pre>import { signal } from &#39;@angular/core&#39;;<br><br>users = signal&lt;any[]&gt;([]);   // writable signal<br>isLoading = signal(false);   // writable boolean<br><br>users.set(newValue) — replace whole value.<br>users.update(prev =&gt; [...prev, newUser]) — update based on old value.</pre><h4><strong>When to use</strong>:</h4><p>local component state, UI flags, lists, small shared store pieces.</p><p>2.computed() — derived/readonly signal <br> (<em>think of </em><strong><em>useMemo()</em></strong><em> in react world)</em></p><p>Calculate values from other signals.</p><pre>import { computed } from &#39;@angular/core&#39;;<br><br>totalUsers = computed(() =&gt; this.users().length);</pre><ul><li>totalUsers() recalculates automatically when users() changes.</li><li>It’s read-only — you cannot set() it.</li></ul><h4>When to use:</h4><p>totals, filtered lists, formatted strings derived from state.</p><p>3. effect() — run side effects<br> (<em>think of </em><strong><em>useEffect()</em></strong><em> in react world)</em></p><p>Run imperative side-effects when signals change.</p><pre>import { effect } from &#39;@angular/core&#39;;<br><br>effect(() =&gt; {<br>  console.log(&#39;Users changed — count:&#39;, this.totalUsers());<br>});</pre><h4><strong>When to use</strong>:</h4><p>logging, trigger some non-state action (e.g., analytics, toast notifications, non-Angular side effects).</p><p>4. input() and output() — component bindings <br> (<em>think of </em><strong><em>props and event callbacks</em></strong> <em>in react world)</em></p><p>Signal-based inputs/outputs for child components (replaces @Input() and @Output() directives).</p><h4>Child component (user-card.component.ts)</h4><pre>import { Component, input, output } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-user-card&#39;,<br>  standalone: true,<br>  template: `<br>    &lt;div&gt;<br>      &lt;strong&gt;{{ user().name }}&lt;/strong&gt;<br>      &lt;button (click)=&quot;remove.emit(user().id)&quot;&gt;Remove&lt;/button&gt;<br>    &lt;/div&gt;<br>  `<br>})<br>export class UserCardComponent {<br>  user = input.required&lt;{ id: number; name: string }&gt;();<br>  remove = output&lt;number&gt;();<br>}</pre><h4>Parent template usage</h4><pre>@for (user of users(); track user.id) {<br>  &lt;app-user-card [user]=&quot;user&quot; (remove)=&quot;onRemove($event)&quot;&gt;&lt;/app-user-card&gt;<br>}</pre><h4><strong>When to use</strong>:</h4><p>clean child → parent event flows, especially when child state is signal-based.</p><p>5. toSignal() — convert Observable → Signal</p><p>Useful when your API or service returns observables but you want a signal in the component.</p><pre>import { toSignal } from &#39;@angular/core/rxjs-interop&#39;;<br><br>usersFromApi = toSignal(this.userService.getUsers$(), { initialValue: [] });</pre><ul><li>toSignal() gives you a read-only signal derived from an observable stream.</li><li>Great when you want to keep using RxJS in services but prefer signals in components.</li></ul><h4><strong>When to use</strong>:</h4><p>when services are RxJS-first (HTTP or websockets) and components prefer signals.</p><blockquote>Now let’s rebuild everything using Angular 20+ Signals — from <strong>API → UI → child → parent</strong>, the modern way.</blockquote><h4>user.service.ts</h4><p>Still uses RxJS HTTP under the hood — but we’ll bridge it with toSignal().</p><pre>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({ providedIn: &#39;root&#39; })<br>export class UserService {<br>  constructor(private http: HttpClient) {}<br><br>  // RxJS Observable<br>  getUsers$(): Observable&lt;any[]&gt; {<br>    return this.http.get&lt;any[]&gt;(&#39;https://jsonplaceholder.typicode.com/users&#39;);<br>  }<br>}</pre><h4>user-dashboard.component.ts</h4><pre>import { Component, signal, computed, effect } from &#39;@angular/core&#39;;<br>import { UserService } from &#39;./user.service&#39;;<br>import { toSignal } from &#39;@angular/core/rxjs-interop&#39;;<br><br>@Component({<br>  selector: &#39;app-user-dashboard&#39;,<br>  templateUrl: &#39;./user-dashboard.component.html&#39;,<br>  standalone: true,<br>})<br>export class UserDashboardComponent {<br>  // Writable signals — store mutable local state<br>  users = signal&lt;any[]&gt;([]);<br>  isLoading = signal(false);<br>  error = signal&lt;string | null&gt;(null);<br><br>  // Derived (computed) signal<br>  totalUsers = computed(() =&gt; this.users().length);<br><br>  constructor(private userService: UserService) {<br>    // Effect runs when totalUsers changes<br>    effect(() =&gt; console.log(&#39;Total users:&#39;, this.totalUsers()));<br><br>    // Initial load<br>    this.loadUsers();<br>  }<br><br>  // Using RxJS observable and converting it into a signal<br>  loadUsers() {<br>    this.isLoading.set(true);<br>    this.error.set(null);<br><br>    const users$ = this.userService.getUsers$();<br>    const usersSignal = toSignal(users$, { initialValue: [] });<br><br>    // React to the emitted value<br>    effect(() =&gt; {<br>      const data = usersSignal();<br>      if (data.length &gt; 0) {<br>        this.users.set(data);<br>        this.isLoading.set(false);<br>      }<br>    });<br>  }<br><br>  // Demonstrating update() and set()<br>  addUser(newUser: any) {<br>    // update() → modify based on previous state<br>    this.users.update(list =&gt; [...list, newUser]);<br>  }<br><br>  removeUser(id: number) {<br>    // set() → replace the signal’s value entirely<br>    this.users.set(this.users().filter(u =&gt; u.id !== id));<br>  }<br>}</pre><h4>user-dashboard.component.html</h4><pre>&lt;div class=&quot;container&quot;&gt;<br>  &lt;h2&gt;User Dashboard (Signals)&lt;/h2&gt;<br><br>  @if (isLoading()) {<br>    &lt;p&gt;Loading users...&lt;/p&gt;<br>  } @else if (error()) {<br>    &lt;p&gt;{{ error() }}&lt;/p&gt;<br>  } @else {<br>    &lt;p&gt;Total users: {{ totalUsers() }}&lt;/p&gt;<br><br>    &lt;ul&gt;<br>      @for (user of users(); track user.id) {<br>        &lt;li&gt;<br>          &lt;user-card<br>            [user]=&quot;user&quot;<br>            (removed)=&quot;removeUser($event)&quot;&gt;<br>          &lt;/user-card&gt;<br>        &lt;/li&gt;<br>      }<br>    &lt;/ul&gt;<br><br>    &lt;button (click)=&quot;addUser({ id: Date.now(), name: &#39;New User&#39; })&quot;&gt;Add User&lt;/button&gt;<br>  }<br>&lt;/div&gt;</pre><h4>user-card.component.ts</h4><pre>import { Component, input, output } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;user-card&#39;,<br>  template: `<br>    &lt;div class=&quot;card&quot;&gt;<br>      &lt;span&gt;{{ user().name }}&lt;/span&gt;<br>      &lt;button (click)=&quot;onRemove()&quot;&gt;Remove&lt;/button&gt;<br>    &lt;/div&gt;<br>  `,<br>  standalone: true,<br>})<br>export class UserCardComponent {<br>  user = input.required&lt;any&gt;();<br>  removed = output&lt;number&gt;();<br><br>  onRemove() {<br>    this.removed.emit(this.user().id);<br>  }<br>}</pre><h3>After Signals — The New Pattern: API → UI → Child → Parent</h3><pre>Step              | Old Way                     | New Way                   <br>--------------    | ------------------------    | ------------------------- <br>API Call          | Observable → Async Pipe     | Observable → `toSignal()` <br>State             | Component properties        | Signals (reactive vars)   <br>Derived Data      | Manual recalculation        | `computed()`              <br>Side Effects      | Subscriptions               | `effect()`                <br>Child → Parent    | `@Output()` EventEmitter    | `output()` Signal         <br>Parent → Child    | `@Input()` Property         | `input()` Signal          </pre><h3>RxJS + Signals — How They Coexist</h3><p>Don’t worry — RxJS isn’t going anywhere.<br> You’ll often:</p><ul><li>Use <strong>RxJS</strong> for async streams, HTTP, and real-time data</li><li>Use <strong>Signals</strong> for local reactive state and UI bindings</li></ul><p>You can easily bridge the two:</p><pre>import { toSignal } from &#39;@angular/core/rxjs-interop&#39;;</pre><p>This gives you the <strong>best of both worlds</strong> — stream-based logic + fine-grained reactivity.</p><h3>When to Use Which Signal?</h3><pre>Signal Type  | Use For                        | Example                    <br>-----------  | ------------------------------ | -------------------------- <br>Writable     | Local mutable state            | API data, toggles, inputs  <br>Computed     | Derived/calculated values      | totals, filters, summaries <br>Effect       | Side effects (log, sync, HTTP) | log total, update title    <br>Input        | Parent → Child data binding    | passing user object        <br>Output       | Child → Parent event binding   | remove, edit, save actions </pre><p>Signals are not a replacement for RxJS, which is still the best tool for complex asynchronous events like HTTP requests. However, Signals simplify the most common reactivity problems in Angular, making the framework more approachable for beginners and more performant for everyone.</p><p>The flow is no longer a guessing game of “when will this component update?”. With Signals, the flow is explicit and direct: a signal changes, and only the things that depend on it react. It’s cleaner, more efficient, and a much smoother developer experience.</p><p>Welcome to the future of Angular reactivity. It’s a great time to start learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abc01471cca0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Components in Angular 20+]]></title>
            <link>https://medium.com/@therahulkshaw/dynamic-components-in-angular-20-23d9dedf0e76?source=rss-5a88aa06f398------2</link>
            <guid isPermaLink="false">https://medium.com/p/23d9dedf0e76</guid>
            <dc:creator><![CDATA[Rahul Shaw]]></dc:creator>
            <pubDate>Sat, 25 Oct 2025 21:33:10 GMT</pubDate>
            <atom:updated>2025-10-25T21:33:10.505Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>1. First, why do we even need dynamic components?</strong></p><p>As an Angular beginner, we are used to defining our component structure in a template. It’s predictable, stable, and easy to understand. You want a &lt;app-my-header&gt;, so you put it in your HTML, and it just shows up. But what if you don&#39;t know ahead of time which component you need?</p><p>Think about these real-world scenarios:</p><ul><li><strong>A generic modal or dialog:</strong> You have a single modal component, but what goes inside it depends on the user’s action. It could be a login form, a “save changes” confirmation, or a contact form. Instead of creating three separate modals, you dynamically load the correct component into one universal modal.</li><li><strong>Dashboard widgets:</strong> Imagine a dashboard where users can customize their layout. They might choose to display a “Sales Chart” widget, a “Latest Orders” list, or a “Customer Support” feed. You don’t know the arrangement of these widgets at compile time. You build the layout with dynamic components.</li><li><strong>Alerts and notifications:</strong> You have different types of alert messages (success, warning, error) that pop up based on what’s happening in your app. Dynamic components let you programmatically show the right alert at the right time and place.</li><li><strong>Wizard or multi-step forms:</strong> You have a complex form that is broken into multiple steps. The component shown at each step depends on the user’s previous answers. Dynamic components make this flow feel seamless.</li></ul><p>In short, dynamic components give you the superpower of <strong>creating components at runtime</strong>, not just when your app first builds. This makes your applications more flexible, reusable, and responsive to user actions.</p><p><strong>2. The new, modern way to do it (Angular 20+)</strong></p><p>In older versions of Angular, this process was a bit clunky, involving something called ComponentFactoryResolver. But with the introduction of standalone components and a streamlined API, it&#39;s now much, much simpler. We&#39;ll be using ViewContainerRef.createComponent().</p><p>Let’s walk through an example. We’ll create a simple app that can show a success or an error message dynamically.</p><p><strong>Step 1: Create the components</strong></p><p>First, let’s create two simple, standalone components that we’ll load dynamically.</p><pre>ng generate component success-message --standalone<br>ng generate component error-message --standalone</pre><p><strong>success-message.component.ts</strong></p><pre>import { Component, input } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-success-message&#39;,<br>  standalone: true,<br>  template: `<br>    &lt;div class=&quot;message success&quot;&gt;<br>      &lt;h3&gt;Success!&lt;/h3&gt;<br>      &lt;p&gt;{{ message() }}&lt;/p&gt;<br>    &lt;/div&gt;<br>  `,<br>  styles: `<br>    .success { background-color: #d4edda; color: #155724; }<br>  `<br>})<br>export class SuccessMessageComponent {<br>  // Use signal-based inputs for modern component communication<br>  message = input.required&lt;string&gt;();<br>}</pre><p><strong>error-message.component.ts</strong></p><pre>import { Component, input } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-error-message&#39;,<br>  standalone: true,<br>  template: `<br>    &lt;div class=&quot;message error&quot;&gt;<br>      &lt;h3&gt;Error!&lt;/h3&gt;<br>      &lt;p&gt;{{ message() }}&lt;/p&gt;<br>    &lt;/div&gt;<br>  `,<br>  styles: `<br>    .error { background-color: #f8d7da; color: #721c24; }<br>  `<br>})<br>export class ErrorMessageComponent {<br>  message = input.required&lt;string&gt;()<br>}</pre><p><strong>Step 2: Set up a placeholder in the parent component</strong></p><p>Next, in our parent component (AppComponent), we need a placeholder where our dynamic component will be inserted. The &lt;ng-container&gt; element is perfect for this because it doesn&#39;t add any extra HTML to the DOM. We&#39;ll give it a template reference variable, #messageContainer.</p><p><strong>app.component.html</strong></p><pre>&lt;div class=&quot;container&quot;&gt;<br>  &lt;h1&gt;Dynamic Messaging Example&lt;/h1&gt;<br>  &lt;div class=&quot;button-row&quot;&gt;<br>    &lt;button (click)=&quot;loadSuccess()&quot;&gt;Show Success&lt;/button&gt;<br>    &lt;button (click)=&quot;loadError()&quot;&gt;Show Error&lt;/button&gt;<br>    &lt;button (click)=&quot;clearContainer()&quot;&gt;Clear&lt;/button&gt;<br>  &lt;/div&gt;<br>  &lt;ng-container #messageContainer&gt;&lt;/ng-container&gt;<br>&lt;/div&gt;</pre><p><strong>Step 3: Access the placeholder and create the component</strong></p><p>Now for the magic in our TypeScript file. We’ll get a reference to our &lt;ng-container&gt; using @ViewChild, which gives us a ViewContainerRef. This reference is our portal for programmatic component creation.</p><p><strong>app.component.ts</strong></p><pre>import { Component, ViewChild, ViewContainerRef, inputBinding } from &#39;@angular/core&#39;;<br>import { SuccessMessageComponent } from &#39;./success-message.component&#39;;<br>import { ErrorMessageComponent } from &#39;./error-message.component&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  standalone: true,<br>  imports: [SuccessMessageComponent, ErrorMessageComponent],<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrl: &#39;./app.component.css&#39;<br>})<br>export class AppComponent {<br>  @ViewChild(&#39;messageContainer&#39;, { read: ViewContainerRef }) <br>  messageContainer!: ViewContainerRef;<br><br>  loadSuccess() {<br>    this.clearContainer(); // Clear previous components<br>    this.messageContainer.createComponent(SuccessMessageComponent, {<br>      bindings: [<br>        inputBinding(&#39;message&#39;, &#39;Your data was submitted successfully!&#39;)<br>      ]<br>    });<br>  }<br><br>  loadError() {<br>    this.clearContainer(); // Clear previous components<br>    this.messageContainer.createComponent(ErrorMessageComponent, {<br>      bindings: [<br>        inputBinding(&#39;message&#39;, &#39;Oops! Something went wrong.&#39;)<br>      ]<br>    });<br>  }<br><br>  clearContainer() {<br>    this.messageContainer.clear(); // Remove all components from the container<br>  }<br>}</pre><p><strong>A quick breakdown of the code:</strong></p><ul><li>@ViewChild(&#39;messageContainer&#39;, { read: ViewContainerRef }): This line gets a reference to our &lt;ng-container&gt; element and tells Angular we want to treat it as a ViewContainerRef, which is the object that can host dynamic components.</li><li>this.clearContainer(): A crucial step! We always clear out any previous components before adding a new one to avoid stacking them up.</li><li>this.messageContainer.createComponent(SuccessMessageComponent, {...}): This is the modern core API call. We pass the component class directly.</li><li>bindings: [inputBinding(&#39;message&#39;, &#39;...&#39;)]: A new, cleaner feature in Angular 20+ for passing data to our dynamic component&#39;s inputs.</li></ul><p><strong>3. Taking it a step further: Handling outputs</strong></p><p>What if your dynamic component needs to communicate back to the parent? With Angular 20+, this is also built into the createComponent options using outputBinding.</p><p>Let’s add a button and an output to our ErrorComponent.</p><p><strong>error-message.component.ts</strong></p><pre>import { Component, input, output } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-error-message&#39;,<br>  standalone: true,<br>  template: `<br>    &lt;div class=&quot;message error&quot;&gt;<br>      &lt;h3&gt;Error!&lt;/h3&gt;<br>      &lt;p&gt;{{ message() }}&lt;/p&gt;<br>      &lt;button (click)=&quot;dismiss.emit()&quot;&gt;Dismiss&lt;/button&gt;<br>    &lt;/div&gt;<br>  `,<br>  styles: `<br>    .error { background-color: #f8d7da; color: #721c24; padding: 1rem; border-radius: 5px; }<br>  `<br>})<br>export class ErrorMessageComponent {<br>  message = input.required&lt;string&gt;();<br>  dismiss = output&lt;void&gt;(); // The signal-based output<br>}</pre><p>Now, update the loadError function in AppComponent to handle the dismiss output.</p><p><strong>app.component.ts</strong></p><pre>import { Component, ViewChild, ViewContainerRef, inputBinding, outputBinding } from &#39;@angular/core&#39;;<br>// ... other imports<br><br><br><br>export class AppComponent {<br>  // ... messageContainer and other functions<br>  loadError() {<br>    this.clearContainer();<br>    this.messageContainer.createComponent(ErrorMessageComponent, {<br>      bindings: [<br>        inputBinding(&#39;message&#39;, &#39;Oops! Something went wrong.&#39;),<br>        outputBinding(&#39;dismiss&#39;, () =&gt; this.handleErrorDismiss())<br>      ]<br>    });<br>  }<br>  handleErrorDismiss() {<br>    console.log(&#39;Error was dismissed by the user!&#39;);<br>    this.clearContainer();<br>  }<br>}</pre><p>Here, outputBinding(&#39;dismiss&#39;, () =&gt; ...) maps the dynamic component&#39;s output event to a method in the parent component. No manual subscription handling needed!</p><p>Dynamic components are a powerful tool for building flexible and interactive user interfaces. They move component creation from a static, compile-time process to a dynamic, runtime one. In modern Angular (20+), the ViewContainerRef is your key. By combining it with @ViewChild and the createComponent method, you can easily insert components, pass data with inputBinding, and react to events with outputBinding. This approach not only cleans up your templates but also opens up a world of possibilities for building truly adaptive applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23d9dedf0e76" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>