<?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 Manolis Xhani Trungu on Medium]]></title>
        <description><![CDATA[Stories by Manolis Xhani Trungu on Medium]]></description>
        <link>https://medium.com/@trmanolis?source=rss-bbd94528d352------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*V9jx9kPm7Eor796VKUgTsw.png</url>
            <title>Stories by Manolis Xhani Trungu on Medium</title>
            <link>https://medium.com/@trmanolis?source=rss-bbd94528d352------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 16:23:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@trmanolis/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[Does anyone know a Kafka Doctor ?]]></title>
            <link>https://levelup.gitconnected.com/does-anyone-know-a-kafka-doctor-757046ccb85e?source=rss-bbd94528d352------2</link>
            <guid isPermaLink="false">https://medium.com/p/757046ccb85e</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[autohealing]]></category>
            <category><![CDATA[clustering]]></category>
            <dc:creator><![CDATA[Manolis Xhani Trungu]]></dc:creator>
            <pubDate>Wed, 14 Jan 2026 19:22:29 GMT</pubDate>
            <atom:updated>2026-01-14T19:22:29.044Z</atom:updated>
            <content:encoded><![CDATA[<h3>Does anyone know a Kafka Doctor ?</h3><p>This article, Heavily Inspired by Pinterest’s Case of creating DoctorKafka, and combines the conceptual benefits of a “Cluster Physician” with the technical architecture outlined in the <strong>DoctorKafka</strong> documentation to provide a comprehensive look at why auto-healing is the future of Kafka management.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6QJAjrRWD5ZiXp8a0z0EsQ.gif" /></figure><h3>From Chaos to Control: Why Your Kafka Infrastructure Needs a “Doctor”</h3><p>In modern data architecture, Apache Kafka is the central nervous system. It handles trillions of events and connects vital microservices. But Kafka is notoriously complex to manage at scale. When a broker fails or slows down, it’s not just a minor glitch — it’s a heart attack for your data pipeline.</p><p>This is why the industry is moving toward autonomous solutions like <strong>DoctorKafka</strong>.</p><h4>1. The Problem: The “Operator’s Burden”</h4><p>Managing a Kafka cluster manually is a high-stakes game of “whack-a-mole.” As clusters grow, three critical pain points emerge:</p><ul><li><strong>The High Cost of Latency:</strong> When a broker’s CPU spikes, performance degrades. Usually, a human operator only notices this <em>after</em> a critical alert fires, by which time data backlogs have already built up.</li><li><strong>The “Over-Provisioning” Trap:</strong> To avoid outages, teams often run clusters at only 30% capacity. You end up paying for massive amounts of unused compute just to handle occasional spikes.</li><li><strong>Operational Toil:</strong> Manual partition reassignment is tedious and error-prone. If a broker fails at 3:00 AM, a human must wake up, diagnose the health of the remaining nodes, and manually shift the load.</li></ul><h4>2. The Solution: A Decentralized “Physician”</h4><p>DoctorKafka replaces manual intervention with a Proof of Concept (PoC) for a self-healing ecosystem. Instead of waiting for a crash, it acts as a <strong>central brain</strong> that continuously analyzes the cluster’s “vital signs.”</p><h3>How the Healing Logic Works</h3><p>The system follows a strict, automated diagnostic loop to ensure the cluster remains healthy:</p><p><strong>Metrics Collection:</strong> “Collectors” (running as processes or sidecars) send CPU, Memory, and Network stats to a dedicated internal topic: _doctor_metrics.</p><p><strong>Continuous Analysis:</strong> The <strong>Doctor Service</strong> consumes these metrics in real-time.</p><p><strong>Autonomous Decision Making:</strong></p><ul><li><strong>The Sneeze:</strong> If CPU usage exceeds <strong>80%</strong>, the broker is flagged as <strong>OVERLOADED</strong>.</li><li><strong>The Heart Attack:</strong> If a heartbeat is missing for more than <strong>10 seconds</strong>, the broker is marked <strong>UNHEALTHY.</strong></li></ul><p><strong>Remedial Action:</strong> The system logs a remedial action (like REASSIGN_PARTITIONS) to the _doctor_actions_log, instantly moving leadership to healthy brokers.</p><h4>3. Scaling for the Real World</h4><p>While the PoC uses a simplified architecture, the path to a production-grade “Doctor” involves high-level engineering strategies:</p><ul><li><strong>Sidecar Deployment:</strong> In Kubernetes, metrics collectors should run as <strong>sidecar containers</strong> or <strong>Java Agents</strong> to gather low-level hardware metrics with near-zero latency.</li><li><strong>High Availability:</strong> To prevent the “Doctor” from becoming a single point of failure, multiple instances should run with <strong>Leader Election</strong> (via Zookeeper) so only one “brain” makes decisions at a time.</li><li><strong>Integration with Cruise Control:</strong> For the heavy lifting of moving terabytes of data, DoctorKafka acts as the high-level decision-maker that triggers <strong>Cruise Control</strong> to execute the actual partition rebalancing.</li></ul><h4>4. The Result: A Resilient Infrastructure</h4><p>By implementing a service like DoctorKafka, organizations gain four transformative benefits:</p><ol><li><strong>Instant Reaction:</strong> It reacts to failures in seconds, faster than any human operator.</li><li><strong>Reduced Toil:</strong> Automates the “boring” parts of cluster maintenance.</li><li><strong>Proactive Prevention:</strong> Detects symptoms (high CPU/Disk) and balances the cluster before it crashes.</li><li><strong>Cost Efficiency:</strong> Run your clusters closer to capacity with the confidence that the “Doctor” will handle the spikes.</li></ol><p>Checkout the repo:</p><p><a href="https://github.com/xhani-manolis-trungu/doctorKafka">https://github.com/xhani-manolis-trungu/doctorKafka</a></p><h4>Conclusion</h4><p>In the era of “set it and forget it” infrastructure, manual checklists are no longer enough. <strong>DoctorKafka</strong> represents a shift toward <strong>Self-Healing Infrastructure</strong> — ensuring your data keeps flowing, your costs stay low, and your engineers get a good night’s sleep.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=757046ccb85e" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/does-anyone-know-a-kafka-doctor-757046ccb85e">Does anyone know a Kafka Doctor ?</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The “Build Once, Deploy Anywhere” Dream: Solving the Angular Config Headache]]></title>
            <link>https://javascript.plainenglish.io/the-build-once-deploy-anywhere-dream-solving-the-angular-config-headache-8104cd02f612?source=rss-bbd94528d352------2</link>
            <guid isPermaLink="false">https://medium.com/p/8104cd02f612</guid>
            <category><![CDATA[runtime-config-angular]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[runtime-configuration]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Manolis Xhani Trungu]]></dc:creator>
            <pubDate>Wed, 07 Jan 2026 13:12:26 GMT</pubDate>
            <atom:updated>2026-01-07T17:22:38.472Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*frWu6d30LTjnb7nQoZrbeg.png" /><figcaption>Runtime config orchestration (Gemini generated image)</figcaption></figure><p>We’ve all been there. You build a beautiful Angular app, and it works perfectly on your machine. Then comes the nightmare: <strong>The Deployment Pipeline.</strong></p><p>Suddenly, you need to change the API URL for staging. Then again for production. Then for that one specific client who needs a custom theme. In the traditional Angular world, this usually leads to a mess of environment files, long build times, and the dreaded “race condition” where your app starts before your settings are even ready.</p><p>Let’s talk about why this happens and how <strong>ngx-config-orchestrator</strong> makes these headaches disappear.</p><h3>The Three Villains of Angular Configuration</h3><h4>1. The Build-Time Trap (environment.ts)</h4><p>Angular’s default way of handling settings is using environment.ts files. It seems simple at first, but it has a huge flaw: <strong>It’s hard-coded.</strong> If you want to change a single variable for your production server, you have to <em>re-build</em> the entire application.</p><ul><li><strong>The Problem:</strong> Re-building takes time (minutes you don’t have during a hotfix).</li><li><strong>The Risk:</strong> You aren’t actually deploying the <em>exact same code</em> you tested in staging. You’re deploying a new build that <em>might</em> have a tiny difference.</li></ul><h4>2. The “Early Bird” Race Condition</h4><p>Some people try to fix this by loading a JSON file at runtime using APP_INITIALIZER. In theory, Angular waits for this to finish before starting.</p><ul><li><strong>The Reality:</strong> It’s a mess. If you have multiple initializers, they often run in parallel.</li><li><strong>The Headache:</strong> Have you ever seen an error like Cannot read property &#39;apiUrl&#39; of undefined? That’s usually because a Service or a Route Guard tried to initialize before your config fetch was finished. You end up writing &quot;if-statements&quot; everywhere just to check if the config is finally there.</li></ul><h4>3. The Boilerplate Mountain</h4><p>This below the “Headache” version that <strong>ngx-config-orchestrator</strong> replaces.</p><h4>Headache 1. The Configuration Model</h4><p>First, you need an interface to keep things type-safe.</p><pre>export interface AppConfig {<br>  apiUrl: string;<br>  featureFlags: {<br>    enableChat: boolean;<br>  };<br>}    </pre><h4>Headache 2. The Configuration Service</h4><p>You need a service to hold the data. But wait — since it’s loaded asynchronously, you have to handle the “not ready yet” state.</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { HttpClient } from &#39;@angular/common/http&#39;;<br>import { firstValueFrom } from &#39;rxjs&#39;;<br><br>@Injectable({ providedIn: &#39;root&#39; })<br>export class ManualConfigService {<br>  private config: AppConfig | null = null;<br><br>  constructor(private http: HttpClient) {}<br><br>  // This is the function the app calls to fetch the JSON<br>  async loadConfig(): Promise&lt;void&gt; {<br>    try {<br>      this.config = await firstValueFrom(<br>        this.http.get&lt;AppConfig&gt;(&#39;/assets/config.json&#39;)<br>      );<br>    } catch (err) {<br>      console.error(&#39;Could not load config!&#39;, err);<br>      // Now you have to decide: stop the app or use defaults?<br>    }<br>  }<br><br>  get settings(): AppConfig {<br>    if (!this.config) {<br>      throw new Error(&#39;Config accessed before loading!&#39;);<br>    }<br>    return this.config;<br>  }<br>}</pre><h4>Headache 3. The APP_INITIALIZER Factory</h4><p>Now you have to hook this into the Angular lifecycle. This is where most developers run into “Race Conditions.” If this isn’t set up perfectly, your other services will try to run before loadConfig finishes.</p><pre>import { APP_INITIALIZER } from &#39;@angular/core&#39;;<br><br>export function initializeAppFactory(configService: ManualConfigService) {<br>  return () =&gt; configService.loadConfig();<br>}</pre><h4>Headache 4. The AppModule Wiring</h4><p>You have to register all of this in your providers. It’s easy to mess up the dependencies here.</p><pre>@NgModule({<br>  providers: [<br>    ManualConfigService,<br>    {<br>      provide: APP_INITIALIZER,<br>      useFactory: initializeAppFactory,<br>      deps: [ManualConfigService],<br>      multi: true<br>    }<br>  ]<br>})<br>export class AppModule { }</pre><h4>Headache 5. The Usage (And the potential crash)</h4><p>Imagine you have an AuthService that needs the apiUrl immediately.</p><pre>@Injectable({ providedIn: &#39;root&#39; })<br>export class AuthService {<br>  constructor(private configService: ManualConfigService) {<br>    // If APP_INITIALIZER isn&#39;t finished, this line crashes your whole app!<br>    console.log(&#39;API URL is:&#39;, this.configService.settings.apiUrl);<br>  }<br>}</pre><p>To do runtime config “the right way” manually, you need:</p><ul><li>A ConfigService.</li><li>An APP_INITIALIZER factory function.</li><li>Error handling for when the JSON fails to load.</li><li>A way to inject these values into other services. That’s a lot of code to write (and maintain) for every single project.</li></ul><h3>Why this is a “Headache”</h3><ol><li><strong>Circular Dependencies:</strong> If your ConfigService needs HttpClient, but you have an HttpInterceptor that needs ConfigService, the app will fail to provide the dependencies.</li><li><strong>Silent Failures:</strong> If the config.json is missing or has a typo, the app might just show a white screen with a cryptic error in the console.</li><li><strong>No Validation:</strong> There’s nothing checking if the JSON actually contains the fields you expect until the app crashes later.</li></ol><p>Enter: ngx-config-orchestrator</p><p>I built <a href="https://www.npmjs.com/package/ngx-config-orchestrator">ngx-config-orchestrator</a> to solve exactly these problems. It’s a “plug-and-play” library that handles the orchestration of your configuration so you don’t have to.</p><h4>The beauty of this simplicity:</h4><pre>import { APP_INITIALIZER, inject } from &quot;@angular/core&quot;;<br>import { provideConfigOrchestrator, ConfigurationService } from &quot;ngx-config-orchestrator&quot;;<br><br>function initAnalytics() {<br>  const configService = inject(ConfigurationService);<br>  const analytics = inject(AnalyticsService);<br><br>  return () =&gt; {<br>    const key = configService.settings().analytics_key;<br>    analytics.initialize(key);<br>  };<br>}<br><br>export const appConfig: ApplicationConfig = {<br>  providers: [<br>    provideConfigOrchestrator({<br>      // These providers run strictly AFTER config is loaded<br>      dependencies: [<br>        {<br>          provide: APP_INITIALIZER,<br>          useFactory: initAnalytics,<br>          multi: true,<br>        },<br>      ],<br>    }),<br>  ],<br>};</pre><p>Why is this better?</p><p><strong>1. Build Once, Run Everywhere</strong> <br>With this library, you can build your Angular app into a Docker image or a static folder <strong>one time</strong>. When you move from Staging to Production, you don’t re-build. You just swap out the config.json file on the server. The app stays the same; the settings change.</p><p><strong>2. Guaranteed Order (No more Race Conditions)</strong> <br>The “Orchestrator” part of the name is key. It ensures that your configuration is fully loaded and validated <strong>before</strong> the rest of your app’s services and guards even wake up. You can safely inject your config into a constructor and <em>know</em> the data is there. No more undefined errors at startup.</p><p><strong>3. Zero Boilerplate</strong> <br>You don’t need to write custom factories or complex APP_INITIALIZER logic. You just provide the path to your config, and the library handles the rest. It’s designed to be &quot;set it and forget it.&quot;</p><p><strong>4. Type Safety</strong> <br>One of the best parts is that it works seamlessly with TypeScript. You can define exactly what your config looks like, and the library ensures your app treats those settings with the respect (and types) they deserve.</p><h4>The Bottom Line</h4><blockquote>Stop fighting with environment.prod.ts and stop worrying if your Route Guard is going to crash because the API URL hasn&#39;t loaded yet.</blockquote><blockquote>By moving to a runtime configuration with <strong>ngx-config-orchestrator</strong>, you get a faster pipeline, a more stable app, and a much happier developer experience. You focus on building features; let the orchestrator handle the settings.</blockquote><p><strong>Ready to clean up your config?</strong> Check out the library on npm: <a href="https://www.npmjs.com/package/ngx-config-orchestrator">ngx-config-orchestrator</a></p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8104cd02f612" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/the-build-once-deploy-anywhere-dream-solving-the-angular-config-headache-8104cd02f612">The “Build Once, Deploy Anywhere” Dream: Solving the Angular Config Headache</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why ABAC Beats RBAC for Custom Permissions: A Developer’s Real-World Case]]></title>
            <link>https://javascript.plainenglish.io/why-abac-beats-rbac-for-custom-permissions-a-developers-real-world-case-73dbcb1d328b?source=rss-bbd94528d352------2</link>
            <guid isPermaLink="false">https://medium.com/p/73dbcb1d328b</guid>
            <category><![CDATA[rbac-access-control]]></category>
            <category><![CDATA[angular-permission]]></category>
            <category><![CDATA[abac-access-control]]></category>
            <category><![CDATA[angular-roles]]></category>
            <category><![CDATA[custom-user-roles]]></category>
            <dc:creator><![CDATA[Manolis Xhani Trungu]]></dc:creator>
            <pubDate>Sat, 13 Sep 2025 15:48:20 GMT</pubDate>
            <atom:updated>2025-09-15T00:15:00.505Z</atom:updated>
            <content:encoded><![CDATA[<p>Struggling with permissions in your app? Learn how I moved from RBAC to ABAC permission systems to handle custom roles and attributes in an Angular application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RpoFll5qvNjIJBC3OmayrQ.png" /></figure><h4>Why ABAC Beats RBAC for Custom Permissions: A Developer’s Real-World Lesson</h4><p>When we started building our application, permissions looked simple enough. Users could comment, admins could manage, and moderators had something in between. Naturally, we kicked things off with a classic <strong>Role-Based Access Control (RBAC)</strong> system.</p><p>It worked — for a while.</p><p>But as soon as we needed <strong>custom roles with nuanced rules based on attributes</strong> (like who created an Article, or whether a task was completed), RBAC started to feel too rigid. That’s when we switched gears and built an <strong>Attribute-Based Access Control (ABAC)</strong> system that finally solved our headaches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j7RT6A7dN_60LhC-pvWHvQ.png" /></figure><p>Here’s a quick walkthrough of that journey.</p><h4>RBAC: The First Attempt</h4><p>RBAC is simple: define roles, give each role permissions, and check them at runtime. Our initial implementation looked something like this:</p><pre>export type User = { roles: Role[]; id: string }<br><br>type Role = keyof typeof ROLES<br>type Permission = (typeof ROLES)[Role][number]<br><br>const ROLES = {<br>  admin: [<br>    &quot;view:comments&quot;,<br>    &quot;create:comments&quot;,<br>    &quot;update:comments&quot;,<br>    &quot;delete:comments&quot;,<br>  ],<br>  moderator: [&quot;view:comments&quot;, &quot;create:comments&quot;, &quot;delete:comments&quot;],<br>  user: [&quot;view:comments&quot;, &quot;create:comments&quot;],<br>} as const<br><br>export function hasPermission(user: User, permission: Permission) {<br>  return user.roles.some(role =&gt;<br>    (ROLES[role] as readonly Permission[]).includes(permission)<br>  )<br>}</pre><p>Usage was straightforward:</p><pre>const user: User = { id: &quot;1&quot;, roles: [&quot;user&quot;] }<br><br>// Can create a comment<br>hasPermission(user, &quot;create:comments&quot;)<br><br>// Can view comments<br>hasPermission(user, &quot;view:comments&quot;)</pre><p>✅ Pros: Easy to read, easy to maintain, works well for simple apps.</p><p>❌ Cons: As soon as we needed context-aware rules (like “users can only update their own articles”), RBAC started to feel like a patchwork of exceptions.</p><h4>The Shift to ABAC</h4><p>We realized our app needed <strong>rules based on attributes</strong> of the user or resource. For example:</p><ul><li>A user can update <strong>only their own comments</strong>.</li><li>An article can be deleted <strong>only if it’s completed and the user is the owner or invited</strong>.</li><li>Users can’t see articles from people who blocked them.</li></ul><p>This is where <strong>ABAC</strong> shines. Instead of just roles and flat permissions, rules can be <strong>functions</strong> that check attributes dynamically.</p><p>Here’s what our ABAC system looked like:</p><pre>type Comment = { id: string; body: string; authorId: string; createdAt: Date }<br>type Article = {<br>  id: string<br>  title: string<br>  userId: string<br>  completed: boolean<br>  invitedUsers: string[]<br>}<br><br>type Role = &quot;admin&quot; | &quot;moderator&quot; | &quot;user&quot;<br>type User = { blockedBy: string[]; roles: Role[]; id: string }<br><br>type PermissionCheck&lt;Key extends keyof Permissions&gt; =<br>  | boolean<br>  | ((user: User, data: Permissions[Key][&quot;dataType&quot;]) =&gt; boolean)<br><br>type Permissions = {<br>  comments: { dataType: Comment; action: &quot;view&quot; | &quot;create&quot; | &quot;update&quot; }<br>  articles: { dataType: Article; action: &quot;view&quot; | &quot;create&quot; | &quot;update&quot; | &quot;delete&quot; }<br>}</pre><p>And here’s how <strong>roles</strong> are defined with attribute checks:</p><pre>const ROLES = {<br>  user: {<br>    comments: {<br>      view: (user, comment) =&gt; !user.blockedBy.includes(comment.authorId),<br>      create: true,<br>      update: (user, comment) =&gt; comment.authorId === user.id,<br>    },<br>    articles: {<br>      view: (user, article) =&gt; !user.blockedBy.includes(article.userId),<br>      create: true,<br>      update: (user, article) =&gt;<br>        article.userId === user.id || article.invitedUsers.includes(user.id),<br>      delete: (user, todo) =&gt;<br>        (article.userId === user.id || article.invitedUsers.includes(user.id)) &amp;&amp;<br>        article.completed,<br>    },<br>  },<br>} as const</pre><p>Now permission checks are way more flexible:</p><pre>const user: User = { blockedBy: [&quot;2&quot;], id: &quot;1&quot;, roles: [&quot;user&quot;] }<br>const article: Article = {<br>  completed: false,<br>  id: &quot;3&quot;,<br>  invitedUsers: [],<br>  title: &quot;Test Todo&quot;,<br>  userId: &quot;1&quot;,<br>}<br><br>// Can create a comment<br>hasPermission(user, &quot;comments&quot;, &quot;create&quot;)<br><br>// Can view a specific todo<br>hasPermission(user, &quot;articles&quot;, &quot;view&quot;, article)</pre><p>✅ Pros: Granular, expressive, handles real-world rules.</p><p>❌ Cons: More complex than RBAC (but worth it for apps with lots of conditions).</p><h4>Lessons Learned</h4><ul><li>Start with RBAC if your app is small. It’s quick and understandable.</li><li>If your rules start sounding like: <em>“but only if the user is the owner, or if it’s completed, unless…”</em> — you’re in <strong>ABAC territory</strong>.</li><li>ABAC adds complexity, but also clarity, because rules live next to the resource they affect.</li></ul><p>For our app, ABAC was the clear winner. It let us encode <strong>business logic directly into the permissions layer</strong> instead of scattering checks across components.</p><p>And that saved us from future headaches.</p><h4>FAQs on ABAC and RBAC Permission Systems</h4><p><strong>1. What is the main difference between RBAC and ABAC?</strong><br> RBAC ties access to roles; ABAC ties access to attributes (user, resource, or context).</p><p><strong>2. Is ABAC always better than RBAC?</strong><br> No. If your app has simple roles and no attribute-based conditions, RBAC is faster to implement.</p><p><strong>3. Does ABAC work well in frontend apps like Angular?</strong><br> Yes — but you’ll need to carefully design your checks so they don’t become spaghetti code.</p><p><strong>4. Can RBAC and ABAC be combined?</strong><br> Absolutely. Many systems use <strong>RBAC for broad rules</strong> and <strong>ABAC for fine-grained control</strong>.</p><p><strong>5. Is ABAC more secure than RBAC?</strong><br> Not necessarily — both can be secure. ABAC just gives you more expressive power.</p><p><strong>6. Which one scales better with large teams?</strong><br> ABAC tends to scale better for <strong>complex, real-world scenarios</strong>, but RBAC is simpler to manage for small teams.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73dbcb1d328b" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/why-abac-beats-rbac-for-custom-permissions-a-developers-real-world-case-73dbcb1d328b">Why ABAC Beats RBAC for Custom Permissions: A Developer’s Real-World Case</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[⚡ Conditional Interceptors in Angular 20]]></title>
            <link>https://medium.com/@trmanolis/conditional-interceptors-in-angular-20-e5c8e85d43c8?source=rss-bbd94528d352------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5c8e85d43c8</guid>
            <category><![CDATA[software-engineer]]></category>
            <category><![CDATA[interesting-reads]]></category>
            <category><![CDATA[interceptors]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Manolis Xhani Trungu]]></dc:creator>
            <pubDate>Thu, 11 Sep 2025 09:28:54 GMT</pubDate>
            <atom:updated>2025-09-14T22:40:41.247Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn how to use <strong>conditional HTTP interceptors in Angular 20</strong> to apply <strong>retry and caching strategies</strong> only where they’re needed. Improve performance, avoid unnecessary logic, and keep your request pipeline clean with practical code examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ta3JiEgO72dgsdo2Mq6Gdw.gif" /><figcaption>Angular Conditional Interceptors</figcaption></figure><p>Retry &amp; Caching Strategies Only Where They Matter</p><p>If you’ve been working with Angular long enough, you’ve probably met <strong>HTTP interceptors</strong>. They’re like little bouncers standing at the door of every HTTP request:</p><ul><li>Need an auth token? 👉 They’ll attach it.</li><li>Want to log everything? 👉 They’ll spam your console.</li><li>Craving retries and caching? 👉 They’ll hook you up.</li></ul><p>But here’s the catch: <strong>not all requests need retries or caching.</strong></p><ul><li>🔑 A <strong>login request</strong> should never retry automatically (unless you <em>really</em> want to lock yourself out after 3 failed attempts).</li><li>📊 An <strong>analytics API</strong> probably doesn’t need caching (who cares how many clicks you had <em>yesterday</em>?).</li><li>🛒 A <strong>product catalog API</strong>? That’s a perfect candidate for retries and caching — because your users expect snappy results when browsing products.</li></ul><p>This is where <strong>conditional interceptors</strong> shine. Instead of blindly applying logic everywhere, we tell Angular:<br> 👉 <em>“Only do this for specific APIs. Don’t waste my time elsewhere.”</em></p><h3>🎯 The Goal</h3><p>Here’s what we’re aiming for:</p><p>✅ Apply <strong>retry logic</strong> only to specific APIs.<br> ✅ Cache results from APIs that benefit from re-use.<br> ✅ Keep the pipeline clean by skipping unnecessary logic.</p><p>Sounds good? Let’s code.</p><h3>💡 Retry Interceptor (Conditional)</h3><p>Retries are great for flaky networks — but disastrous for sensitive endpoints like login. Let’s apply retries only to our <strong>catalog API</strong>.</p><pre>import { HttpInterceptorFn } from &#39;@angular/common/http&#39;;<br>import { retry } from &#39;rxjs&#39;;<br><br>export const retryInterceptor: HttpInterceptorFn = (req, next) =&gt; {<br>  const shouldRetry = req.url.includes(&#39;/api/catalog&#39;);<br><br>  if (shouldRetry) {<br>    return next(req).pipe(<br>      retry(3) // 🔄 retry failed requests up to 3 times<br>    );<br>  }<br><br>  return next(req); // 🚫 no retry for other endpoints<br>};</pre><p>👉 Here we only retry /api/catalog requests. Login, auth, and other APIs are left untouched (your account is safe 🎉).</p><h3>💡 Simple Caching Interceptor (Conditional)</h3><p>Nobody likes waiting for the same data twice. Let’s add a simple in-memory cache, again only for /api/catalog.</p><pre>import { HttpInterceptorFn } from &#39;@angular/common/http&#39;;<br>import { of, tap } from &#39;rxjs&#39;;<br><br>const cache = new Map&lt;string, any&gt;();<br><br>export const cachingInterceptor: HttpInterceptorFn = (req, next) =&gt; {<br>  const isCacheable = req.method === &#39;GET&#39; &amp;&amp; req.url.includes(&#39;/api/catalog&#39;);<br><br>  if (isCacheable) {<br>    const cachedResponse = cache.get(req.url);<br><br>    if (cachedResponse) {<br>      console.log(&#39;📦 Returning cached response for&#39;, req.url);<br>      return of(cachedResponse); // ✅ serve from cache<br>    }<br><br>    return next(req).pipe(<br>      tap((event) =&gt; {<br>        cache.set(req.url, event); // 💾 store in cache<br>      })<br>    );<br>  }<br><br>  return next(req); // 🚫 no caching for other requests<br>};</pre><p>👉 This way, repeated GET /api/catalog/... requests are blazing fast. Other endpoints? Business as usual.</p><h3>⚙️ Conditional Composition</h3><p>Now let’s combine caching + retry into a <strong>single conditional interceptor</strong>.</p><pre>import { HttpInterceptorFn } from &#39;@angular/common/http&#39;;<br>import { cachingInterceptor } from &#39;./caching.interceptor&#39;;<br>import { retryInterceptor } from &#39;./retry.interceptor&#39;;<br><br>export const conditionalApiInterceptor: HttpInterceptorFn = (req, next) =&gt; {<br>  const isCatalogApi = req.url.includes(&#39;/api/catalog&#39;);<br><br>  if (isCatalogApi) {<br>    // 🌀 Compose caching + retry<br>    return cachingInterceptor(req, (cachedReq) =&gt;<br>      retryInterceptor(cachedReq, next)<br>    );<br>  }<br><br>  // 🚫 Fallback: no special logic<br>  return next(req);<br>};</pre><p>👉 Magic!</p><ul><li>Catalog requests get both <strong>caching &amp; retry</strong>.</li><li>Other requests cruise straight through untouched.</li></ul><h3>🔌 Registering the Interceptors</h3><p>Finally, let’s wire everything up in Angular 20.</p><pre>import { bootstrapApplication } from &#39;@angular/platform-browser&#39;;<br>import { provideHttpClient, withInterceptors } from &#39;@angular/common/http&#39;;<br>import { AppComponent } from &#39;./app/app.component&#39;;<br>import { conditionalApiInterceptor } from &#39;./app/interceptors/conditional-api.interceptor&#39;;<br><br>bootstrapApplication(AppComponent, {<br>  providers: [<br>    provideHttpClient(<br>      withInterceptors([conditionalApiInterceptor])<br>    ),<br>  ],<br>});</pre><p>That’s it. Your app now has <strong>context-aware retries and caching</strong>. 🎉</p><h3>🚀 Benefits</h3><p>✅<strong>Granular control</strong> — retries/caching only where they’re safe.</p><p>✅<strong>Performance boost</strong> — no more wasted network calls.</p><p>✅<strong>Cleaner code</strong> — no bloated if statements everywhere.</p><h3>🔮 Real-World Use Cases</h3><p>✅ Retry <strong>catalog/product listing APIs</strong> but never login requests.</p><p>✅ Cache <strong>user profile data</strong> for smoother navigation.</p><p>✅ Apply <strong>special logic only in production</strong> (keep dev logs noisy).</p><h3>📝 Takeaway</h3><p>Conditional interceptors in Angular 20 make your HTTP pipeline <strong>smart, fast, and drama-free</strong>. Instead of spamming all requests with retries or caching, you only enhance the ones that truly matter.</p><p>This pattern keeps your code <strong>clean</strong>, <strong>reliable</strong>, and <strong>ready to scale</strong>.</p><p>⚡ Bonus: You can even pair this with <strong>feature flags</strong> to toggle retries/caching at runtime — no redeploys needed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5c8e85d43c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tracking Changes in Angular Forms]]></title>
            <link>https://javascript.plainenglish.io/tracking-changes-in-angular-forms-2b9a2aec25e2?source=rss-bbd94528d352------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b9a2aec25e2</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[angular-froms]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-forms]]></category>
            <dc:creator><![CDATA[Manolis Xhani Trungu]]></dc:creator>
            <pubDate>Tue, 09 Sep 2025 10:39:30 GMT</pubDate>
            <atom:updated>2025-09-14T22:39:44.572Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tracking Changes in Angular Forms Without Losing Your Mind 🤯</h3><p>If you’ve spent more than five minutes as an Angular developer, you’ve probably wrestled with forms. They’re everywhere — login screens, checkout flows, massive onboarding wizards that make you question life choices.</p><p>And hey, don’t get me wrong — Angular forms are powerful. But let’s be real: sometimes you just wanna know <em>what actually changed</em> without swimming through a sea of boilerplate subscriptions and giant form objects. Like, if a user just updated their street name, why should you care about the fact their hobbies array is still intact?</p><p>That’s exactly the itch I had, and — spoiler alert — I scratched it with a neat little utility that tracks changes like a pro.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PKO3uWosri48XA9nmQwqgQ.png" /></figure><h3>Why the Usual Way Feels Like Overkill 🐘💨</h3><p>Sure, you can always subscribe to formControl.valueChanges. Easy peasy… until you’ve got a form with a nested FormGroup for addresses, a FormArray for hobbies, and who knows what else.</p><p>The problem? A single change anywhere in that giant form blasts the whole form value at you. Boom. Every time. All of it.</p><p>It’s like asking someone “Did you move your desk a little?” and they respond by shipping you the blueprint of the entire office building. Not helpful.</p><h3>Enter the Hero: A Smart Diff Utility 🦸‍♂️</h3><p>So here’s the cool part. Instead of drowning in form values, I cooked up a simple utility that does two magical things:</p><ol><li><strong>Performance win</strong>: It waits for the user to <em>pause typing</em> before it even bothers checking changes. (Because nobody wants to diff JSON objects on every keystroke.</li><li><strong>Crystal clarity</strong>: It gives you a clean, tidy “diff” object showing <em>only what actually changed</em>.</li></ol><p>Think of it like having a friend who only tells you the juicy gossip, not the whole town’s history.</p><h3>The Magic Sauce 🍝 (a.k.a. Code)</h3><p>Here’s the core of our utility:</p><pre>/**<br> * Recursively computes a &quot;diff&quot; object between two values.<br> * Returns null if the values are identical.<br> * For objects, it returns a new object with only the changed properties.<br> * For arrays, it returns a new array with a diff for each element.<br> */<br>function getDiff(original: any, current: any): any {<br>  if (original === current) {<br>    return null;<br>  }<br><br>  // Handle nested objects (FormGroups)<br>  if (original !== null &amp;&amp; typeof original === &#39;object&#39; &amp;&amp; !Array.isArray(original) &amp;&amp;<br>      current !== null &amp;&amp; typeof current === &#39;object&#39; &amp;&amp; !Array.isArray(current)) {<br>    const diff: any = {};<br>    let hasChanges = false;<br>    for (const key in current) {<br>      if (Object.prototype.hasOwnProperty.call(current, key)) {<br>        const itemDiff = getDiff(original[key], current[key]);<br>        if (itemDiff !== null) {<br>          diff[key] = itemDiff;<br>          hasChanges = true;<br>        }<br>      }<br>    }<br>    return hasChanges ? diff : null;<br>  }<br><br>  // Handle arrays (FormArrays)<br>  if (Array.isArray(original) &amp;&amp; Array.isArray(current)) {<br>    const diff: any[] = [];<br>    let hasChanges = false;<br>    const maxLength = Math.max(original.length, current.length);<br>    for (let i = 0; i &lt; maxLength; i++) {<br>      const itemDiff = getDiff(original[i], current[i]);<br>      diff[i] = itemDiff;<br>      if (itemDiff !== null) {<br>        hasChanges = true;<br>      }<br>    }<br>    return hasChanges ? diff : null;<br>  }<br><br>  // Handle primitive types<br>  return current;<br>}</pre><p>And here’s the wrapper that ties it all together:</p><pre>export function trackFormChanges(control: AbstractControl, initialValue: any): Subscription {<br>  return control.valueChanges<br>    .pipe(debounceTime(300))<br>    .subscribe(currentValue =&gt; {<br>      const diff = getDiff(initialValue, currentValue);<br>      console.log(&quot;Changes detected:&quot;, diff);<br>    });<br>}</pre><h3>Breakdown of the Code</h3><ul><li><strong>getDiff(original, current):</strong> This is the heart of the utility. It&#39;s a recursive function that compares the original form value (our baseline) with the current value.</li><li>If the values are identical, it returns null.</li><li>If they are objects (FormGroups), it iterates over the keys and calls itself on each property to find nested changes. It only adds properties to the diff object if a change is found.</li><li>If they are arrays (FormArrays), it iterates over the elements and calls itself to find changes.</li><li>For primitive values (strings, numbers), it simply returns the new value.</li><li><strong>trackFormChanges(control, initialValue):</strong> This is the public function you&#39;ll use in your component.</li><li>It takes the form control you want to track and its initialValue.</li><li>It subscribes to the valueChanges observable of the root control.</li><li>The debounceTime(300) operator waits for 300 milliseconds of inactivity before emitting a value. This is crucial for performance, as it prevents the diff function from running on every single keystroke.</li><li>Once a value is emitted, it calls getDiff and logs the resulting diff object.</li></ul><h3>Why I Fell in Love with This 💘</h3><p>The first time I tried it, I was building a user profile form with nested groups. Normally, I’d have to check dirty states on every field like a detective with too much coffee. But with this? One neat diff object, clear as day.</p><p>Suddenly, enabling a <strong>“Save” button only when something actually changed</strong> went from a gnarly headache to a one-liner:</p><pre>&lt;button [disabled]=&quot;!hasChanges&quot;&gt;Save&lt;/button&gt;</pre><p>Chef’s kiss. 👌</p><h3>A Real-Life Example: User Profile Form 🧑‍💻</h3><p>Here’s how it looks in action:</p><pre>@Component({...})<br>export class UserProfileComponent implements OnInit, OnDestroy {<br>  userForm: FormGroup;<br>  private formSubscription: Subscription;<br>  public hasChanges = false;<br><br>  constructor(private fb: FormBuilder) {<br>    this.userForm = this.fb.group({<br>      name: [&#39;John Doe&#39;, Validators.required],<br>      address: this.fb.group({<br>        street: [&#39;123 Angular Ave&#39;],<br>        city: [&#39;Codeville&#39;]<br>      })<br>    });<br>  }<br><br>  ngOnInit() {<br>    const initialValue = this.userForm;<br>    this.formSubscription = this.userForm.valueChanges<br>      .pipe(debounceTime(300))<br>      .subscribe(() =&gt; {<br>        const diff = getDiff(initialValue, this.userForm.value);<br>        this.hasChanges = diff !== null;<br>      });<br>  }<br><br>  ngOnDestroy() {<br>    if (this.formSubscription) {<br>      this.formSubscription.unsubscribe();<br>    }<br>  }<br><br>  onSave() {<br>    if (this.hasChanges) {<br>      console.log(&#39;Saving changes:&#39;, getDiff(this.userForm, this.userForm.value));<br>    }<br>  }<br>}</pre><p>It’s simple, clean, and doesn’t leave you second-guessing what’s happening under the hood.</p><h3>Wrapping Up 🎁</h3><p>Forms can be messy, but tracking changes doesn’t have to be. With a smart recursive diff and a little debounce magic, you get a <strong>reliable, testable, and sanity-saving</strong> way to know exactly what’s changed — nothing more, nothing less.</p><p>I’ve been using this trick across projects, and honestly, I don’t want to go back. If you’re tired of wrestling with dirty and touched states, give this a spin.</p><p>Who knows — you might just fall in love with Angular forms again. (Okay, maybe that’s pushing it. 😅)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b9a2aec25e2" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/tracking-changes-in-angular-forms-2b9a2aec25e2">Tracking Changes in Angular Forms</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Angular Forms with Mapping Objects: Scalable Validation Made Simple]]></title>
            <link>https://medium.com/@trmanolis/mastering-angular-forms-with-mapping-objects-scalable-validation-made-simple-53a36c8e6221?source=rss-bbd94528d352------2</link>
            <guid isPermaLink="false">https://medium.com/p/53a36c8e6221</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-forms]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[declarative-programming]]></category>
            <dc:creator><![CDATA[Manolis Xhani Trungu]]></dc:creator>
            <pubDate>Mon, 08 Sep 2025 10:17:31 GMT</pubDate>
            <atom:updated>2025-09-08T10:17:31.137Z</atom:updated>
            <content:encoded><![CDATA[<p>Discover how mapping objects can simplify complex Angular reactive forms. Learn to manage nested form groups, dynamic validators, and conditional logic with a clean, scalable approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tJUWaSGQQt2x76QiZd4ekA.png" /></figure><blockquote>Angular Forms Made Easy with the Mapping Paradigm</blockquote><p>If you’ve ever built a complex <strong>onboarding form</strong> in Angular, you know the pain:</p><ul><li>Dozens of fields, grouped into sub-forms.</li><li>Each field having its own set of validators.</li><li>And the kicker: <strong>dynamic rules</strong> that change depending on user input.</li></ul><p>Without structure, your form code quickly becomes a <strong>graveyard of </strong><strong>if/else statements</strong>. And trust me, nothing good ever comes out of a 300-line function just to toggle validators.</p><p>This is where <a href="https://medium.com/@trmanolis/map-vs-switch-ifs-in-typescript-cleaner-code-faster-lookups-c85f4f2487d3"><strong>Mapping objects</strong> </a>shine. Instead of burying rules inside conditionals, we can <strong>declare them once</strong> in a mapping, and let Angular’s forms react accordingly.</p><p>Let’s walk through this step by step 👇</p><h4>📝 The Setup: Parent &amp; Child Forms</h4><p>Imagine we’re building an <strong>Onboarding Form</strong>. At the top level, we have a <strong>parent form</strong> that groups together several child forms:</p><pre>const onBoardingForm = new FormGroup({<br>  personalDetails: this.personalDetailsForm(null),<br>  contactDetails: this.contactDetailsForm(null),<br>  addressDetails: this.addressDetailsForm(null)<br>});</pre><ul><li>Each <strong>child form</strong> (personalDetailsForm, contactDetailsForm, etc.) is its own FormGroup.</li><li>Each child form has its own fields, validators, and sometimes even <strong>conditional visibility rules</strong>.</li></ul><p>Looks clean, right? But here’s where things get messy.</p><h4>🚨 The Problem with Traditional Validation</h4><p>Let’s zoom into the <strong>Contact Details</strong> form.</p><p>You might have fields like:</p><ul><li>postalCode → required if the communication type is <em>address</em>.</li><li>postOfficeBox → required only if communication mode = <em>post</em> <strong>and</strong> type = <em>P.O. Box</em>.</li><li>postOffice → required only if communication mode = <em>post</em> <strong>and</strong> type = <em>P.O.</em>.</li></ul><p>If you try to do this with conditionals, you’ll quickly end up with a Hydra like this:</p><pre>if (communicationMode === 1500020 &amp;&amp; communicationType === 1500004) {<br>  // setValidators for postOfficeBox<br>}<br>if (communicationMode === 1500020 &amp;&amp; communicationType === 1500005) {<br>  // setValidators for postOffice<br>}<br>if (communicationType === 1500001) {<br>  // setValidators for addressName, addressNumber, postalCode...<br>}</pre><p>And so on.<br> Not only does this clutter the form initialization, but it also makes <strong>adding a new rule painful</strong>. You’d have to chase conditionals across multiple files.</p><p>Let’s face the hard truth …. many of us have written this kind of code. We can change it , no worry.</p><h4>✅ The Mapping Paradigm to the Rescue</h4><p>Instead of imperative if/else logic, we <strong>declare rules</strong> in a <strong>mapping object</strong>.</p><p>We start with a reusable config type:</p><pre>export type CxOnboardingFieldsConfig = {<br>  [key: string]: {<br>    required?: (...args: any) =&gt; boolean;<br>    show?: (...args: any) =&gt; boolean;<br>    clear?: (...args: any) =&gt; boolean;<br>  };<br>};</pre><p>This lets us say, in plain English:</p><ul><li>“This field is required if X.”</li><li>“This field is visible if Y.”</li><li>“This field should be cleared if Z.”</li></ul><p>Example: Address Form Config</p><p>Here’s what the rules look like in practice:</p><pre>const AddressFieldsConfig: CxOnboardingFieldsConfig = {<br>  addressName: {<br>    required: (communicationMode, communicationType) =&gt;<br>      communicationType == 1500001,<br>  },<br>  addressNumber: {<br>    required: (communicationMode, communicationType) =&gt;<br>      communicationType == 1500001,<br>  },<br>  postalCode: {<br>    required: () =&gt; true,<br>  },<br>  city: {<br>    required: () =&gt; true,<br>  },<br>  country: {<br>    required: () =&gt; true,<br>  },<br>  postOfficeBox: {<br>    required: (communicationMode, communicationType) =&gt;<br>      communicationMode == 1500020 &amp;&amp; communicationType == 1500004,<br>  },<br>  postOffice: {<br>    required: (communicationMode, communicationType) =&gt;<br>      communicationMode == 1500020 &amp;&amp; communicationType == 1500005,<br>  },<br>};</pre><p>No if/else spaghetti. Just <strong>pure declarative mapping</strong>.<br> Want to add a new rule? Just drop a new entry in the config.</p><h4>🔧 Initializing the Form</h4><p>Here’s how the form setup looks with mappings and a shared validator map:</p><pre>export const CxOnboardingValidators: ValidatorsMap = {<br>  ADDRESS: {<br>    communicationMode: [Validators.required],<br>    preferredFlag: [Validators.required],<br>    communicationType: [Validators.required],<br>    postalCode: [Validators.required],<br>    city: [Validators.required],<br>    country: [Validators.required],<br>  },<br>};</pre><pre>export function initAddressForm(address: any, initialAddress = false) {<br>  const form = new FormGroup({<br>    communicationMode: new FormControl(null, CxOnboardingValidators.ADDRESS.communicationMode),<br>    preferredFlag: new FormControl(address?.preferredFlag || false, CxOnboardingValidators.ADDRESS.preferredFlag),<br>    communicationType: new FormControl(null, CxOnboardingValidators.ADDRESS.communicationType),<br>    addressName: new FormControl(null),<br>    addressNumber: new FormControl(null),<br>    postalCode: new FormControl(null, CxOnboardingValidators.ADDRESS.postalCode),<br>    city: new FormControl(null, CxOnboardingValidators.ADDRESS.city),<br>    country: new FormControl(null, CxOnboardingValidators.ADDRESS.country),<br>    postOfficeBox: new FormControl(),<br>    postOffice: new FormControl(),<br>  });<br><br>  // Example: lock initial address<br>  if (initialAddress) {<br>    form.get(&#39;communicationMode&#39;).setValue(1500002);<br>    form.get(&#39;communicationMode&#39;).disable();<br>    form.get(&#39;preferredFlag&#39;).setValue(true);<br>  }<br><br>  // Apply dynamic mapping rules<br>  handleAddressChange(form);<br><br>  return form;<br>}</pre><p>Notice how the <strong>validators</strong> and <strong>dynamic rules</strong> are now completely <strong>declarative</strong>.</p><h4>🎯 Why This Matters</h4><p>This mapping approach has some huge wins:</p><ul><li>✅ <strong>No duplication</strong> → All rules are centralized in mapping objects.</li><li>✅ <strong>Easy to extend</strong> → Adding a new field or condition = new entry in the map.</li><li>✅ <strong>Separation of concerns</strong> → Validators live in one place, forms in another.</li><li>✅ <strong>Readable</strong> → Anyone looking at the config instantly understands the rules.</li></ul><p>Compare this to chasing down if/else blocks across five files… no thanks.</p><h4>⚡ Real-World Impact</h4><p>In a real project, I used this exact approach to manage a <strong>dynamic modal configuration system (20 different types of dialogs/modals)</strong>. Each modal (prompt, confirm, overwrite, etc.) had its own:</p><ul><li>Title</li><li>Description</li><li>CSS classes</li><li>Buttons (with label, action, type, color)</li></ul><p>Instead of hardcoding logic in every modal component, I created a <strong>mapping object</strong>:</p><pre>export const MODAL_CONFIG_MAP: Record&lt;ModalType, (actions: Partial&lt;DialogActions&gt;) =&gt; ModalConfig&gt; = {<br>  prompt: (actions) =&gt; ({<br>    data: {<br>      title: &#39;Process&#39;,<br>      description: &#39;...&#39;,<br>      buttons: [<br>        { text: &#39;Skip&#39;, onClick: actions.onSkip, style: &#39;default&#39;, color: &#39;main&#39; },<br>        { text: &#39;Continue&#39;, onClick: actions.onStarteProcess, style: &#39;fill&#39;, color: &#39;main&#39; },<br>      ],<br>    },<br>  }),<br>  // ...other modal types<br>};</pre><p>Need a new modal? Just add a new mapping entry.<br> Zero duplication, zero chaos.</p><h4>📊 A Word on Performance</h4><p>This isn’t just about cleaner code — it’s also about <strong>performance</strong>.</p><ul><li>With if/else or switch, adding more conditions means <strong>linear growth (O(n))</strong> in checks.</li><li>With mapping objects, lookup is <strong>constant time (O(1))</strong>, since keys map directly to rules.</li></ul><p>On small forms, you won’t notice. But at scale (dozens of fields, hundreds of rules), this can make validations <strong>significantly faster</strong> and the codebase <strong>much easier to maintain</strong>.</p><h4>🚀 Wrapping Up</h4><p>The <strong>Mapping Paradigm</strong> is your best friend when dealing with <strong>dynamic, complex forms</strong> in Angular.</p><ul><li>Centralized config → no spaghetti conditionals.</li><li>Declarative rules → easy to read, easy to extend.</li><li>Better performance → O(1) lookups instead of endless checks.</li></ul><p>Whether it’s forms, modals, or UI logic, remember: <strong>map it, don’t branch it.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53a36c8e6221" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Map vs Switch & Ifs in TypeScript: Cleaner Code & Faster Lookups]]></title>
            <link>https://javascript.plainenglish.io/map-vs-switch-ifs-in-typescript-cleaner-code-faster-lookups-c85f4f2487d3?source=rss-bbd94528d352------2</link>
            <guid isPermaLink="false">https://medium.com/p/c85f4f2487d3</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Manolis Xhani Trungu]]></dc:creator>
            <pubDate>Wed, 03 Sep 2025 12:56:01 GMT</pubDate>
            <atom:updated>2025-09-14T22:40:04.609Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sW_eS4WtylbsEkFZgiEtzw.png" /><figcaption>Mapping vs Switch/If statements</figcaption></figure><p>Learn how using mapping objects in TypeScript replaces bulky switch/if statements, simplifies code maintenance, and improves performance with O(1) lookups.</p><p>Let’s be honest — we’ve all been there. <br>You start with a simple conditional. Then add a second one. Then add a “quick” switch. <br>A month later there is a requirement somewhere in the fine prints that needs another if statement. Then your function looks like it’s auditioning for a spaghetti western.</p><p>Before you know it, you’re scrolling for miles through something like this:</p><pre>if (role === &#39;admin&#39;) {<br>  // do admin stuff<br>} else if (role === &#39;editor&#39;) {<br>  // do editor stuff<br>} else if (role === &#39;guest&#39;) {<br>  // do guest stuff<br>} else if (role === &#39;superAdmin&#39;) {<br>  // unleash the super powers<br>} else {<br>  // default behavior<br>}</pre><p>This works fine… until you need to add one more role to the table, or change behavior for just one of them. <br>That’s when you start wondering if you should add another <strong><em>else if</em></strong>, <strong>OR </strong>finally <strong><em>just move to the mountains and raise goats</em>.</strong></p><h3>🎯 The Core Idea — Map Your Logic Instead</h3><p>Instead of scattering your logic through nested conditionals, you can keep <strong>all possible behaviors</strong> in <strong>one object, </strong>and simply look them up by key.</p><p>Think of it as a dictionary for your code’s possible status:</p><pre>const ROLE_ACTIONS: Record&lt;string, () =&gt; void&gt; = {<br>  admin: () =&gt; console.log(&#39;Showing admin dashboard&#39;),<br>  editor: () =&gt; console.log(&#39;Opening article editor&#39;),<br>  guest: () =&gt; console.log(&#39;Showing public content&#39;),<br>  superAdmin: () =&gt; console.log(&#39;Launching God Mode 🚀&#39;),<br>};<br><br>function handleRole(role: string) {<br>  ROLE_ACTIONS[role]?.() ?? console.warn(&#39;Unknown role&#39;);<br>}<br><br>handleRole(&#39;editor&#39;); // &quot;Opening article editor&quot;</pre><p>Why is this <strong>nice?</strong></p><ul><li>You <strong>remove branching</strong> from the main logic.</li><li>Adding a new role = <strong>just add another key in the map</strong>.</li><li>It’s easier to <strong>read</strong>, <strong>test</strong>, and <strong>maintain</strong>.</li><li>You can <strong>pass data dynamically</strong> without altering the whole flow.</li></ul><h3>🛠 Real-World Angular Example — Dynamic Modal Configurations</h3><p>Here’s a real case where I had to use this approach: <br>I was building a <strong>modal/dialog system </strong>in Angular, and the requirements were… let’s say generous.</p><p>We had multiple modal types, each with:</p><ul><li><strong>Title</strong></li><li><strong>Description</strong></li><li><strong>CSS class names</strong> for styling</li><li><strong>Buttons</strong> (label, action, type, color)</li><li>Sometimes <strong>custom templates or components</strong></li></ul><p>Initially, it was tempting to write:</p><pre>if (modalType === &#39;prompt&#39;) {<br>  // return prompt modal config<br>} else if (modalType === &#39;dataLoss&#39;) {<br>  // return data loss modal config<br>} else if ...</pre><p>But with 10+ modals with similar layout and different context and content, and more being added later, this would become a nightmare.</p><h3>The Mapping Approach</h3><p>Instead of branching, I created a <strong>mapping object</strong> where:</p><ul><li>Keys = modal type</li><li>Value = function returning the modal configuration</li><li>Function receives the <strong>actions</strong> object so button handlers are dynamic</li></ul><pre>export const MODAL_CONFIG_MAP: Record&lt;ModalType, (actions: Partial&lt;DialogActions&gt;) =&gt; ModalConfig&gt; = {<br>  prompt: (actions) =&gt; ({<br>    data: {<br>      title: &#39;Υπηρεσία&#39;,<br>      status: &#39;info&#39;,<br>      description: `Για γρήγορη και ακριβή συμπλήρωση...`,<br>      buttons: [<br>        { text: &#39;Παράβλεψη&#39;, onClick: actions.onSkip, style: &#39;default&#39;, color: &#39;main&#39; },<br>        { text: &#39;΄Εναρξη&#39;, onClick: actions.onStart, style: &#39;fill&#39;, color: &#39;main&#39; },<br>      ]<br>    }<br>  }),<br>  dataLoss: (actions) =&gt; ({<br>    data: {<br>      title: &#39;Ανανέωση&#39;,<br>      status: &#39;info&#39;,<br>      description: `Πρόκειται να εφαρμόσετε μια διαδικασία...`,<br>      buttons: [<br>        { text: &#39;Ακύρωση&#39;, onClick: actions.onDismiss, style: &#39;default&#39;, color: &#39;main&#39; },<br>        { text: &#39;Συνέχεια&#39;, onClick: actions.onConfirm, style: &#39;fill&#39;, color: &#39;main&#39; },<br>      ]<br>    }<br>  }),<br>  // ... other modal types<br>};</pre><h4>How it’s used</h4><pre>openModal(type: ModalType, actions: Partial&lt;DialogActions&gt;) {<br>  const config = MODAL_CONFIG_MAP[type]?.(actions);<br>  if (config) {<br>    this.modalService.open(config);<br>  } else {<br>    console.warn(`Unknown modal type: ${type}`);<br>  }<br>}</pre><p><strong>Result</strong>:<br> When a new modal is needed → I <strong>just add a new entry</strong> to MODAL_CONFIG_MAP.<br> No touching existing logic. No risk of breaking other cases.</p><h3>📦 Another Example — Dynamic Form Field Rules</h3><p>This works beyond modals.<br> For example, instead of:</p><pre>if (fieldType === &#39;email&#39;) {<br>  return Validators.email;<br>} else if (fieldType === &#39;phone&#39;) {<br>  return phoneValidator;<br>} else if ...</pre><p>You can do:</p><pre>const FIELD_VALIDATORS: Record&lt;string, ValidatorFn&gt; = {<br>  email: Validators.email,<br>  phone: phoneValidator,<br>  age: Validators.min(18)<br>};<br><br>function getValidator(type: string) {<br>  return FIELD_VALIDATORS[type] ?? Validators.nullValidator;<br>}</pre><h3>⏱ Performance Gains — Big O Perspective</h3><p>Another often overlooked benefit of the mapping approach is <strong>performance</strong>, especially when you have <strong>many cases</strong>.</p><p><strong>Classic </strong><strong>if / </strong><strong>else if chain:</strong><br> Each condition is evaluated in order until a match is found.<br> In the worst case (last branch), you check <strong>all N conditions</strong>.<br> <strong>Time complexity:</strong> O(N)</p><p><strong>switch statement:</strong><br> Similar behavior as if/else if in most JavaScript engines.<br> Often optimized for contiguous integers, but for strings, it’s usually <strong>linear</strong>: O(N)</p><p><strong>Mapping object / dictionary lookup:</strong><br> Accessing a key in an object is typically <strong>O(1)</strong> — constant time, regardless of how many cases you have.</p><p>So, as your app grows and you add more modal types, roles, or form field types, <strong>lookup maps scale much better</strong>.</p><pre>const ROLE_ACTIONS: Record&lt;string, () =&gt; void&gt; = {<br>  admin: () =&gt; {...},<br>  editor: () =&gt; {...},<br>  guest: () =&gt; {...},<br>  superAdmin: () =&gt; {...},<br>};<br><br>ROLE_ACTIONS[userRole]?.(); // O(1)</pre><blockquote>💡 <strong>Takeaway:</strong> Not only is your code cleaner and easier to maintain, but it’s also faster and more predictable as your number of cases grows.</blockquote><h3>🎉 The Payoff</h3><p>With this mapping approach:</p><ul><li>Your logic becomes <strong>declarative</strong> — you <em>describe</em> what to do, instead of controlling every branch manually.</li><li>Your code becomes <strong>extensible</strong> — adding a case is as simple as adding a key.</li><li>Your main function stays <strong>short and sweet</strong> — it’s just a lookup.</li></ul><h3>✅ Summary</h3><ul><li><strong>Map your logic</strong> instead of scattering if/else or switch.</li><li><strong>Centralize configuration</strong> (modal configs, validators, actions, etc.).</li><li><strong>Add new cases</strong> without touching existing logic.</li><li><strong>Big O boost</strong>: from O(N) linear checks → O(1) constant-time lookup.</li><li><strong>Result:</strong> cleaner code, safer extensions, and better runtime performance.</li></ul><h3>TL;DR</h3><blockquote>If you find yourself writing <strong>multiple if/else or switch cases</strong>,<br> ask yourself:<br> “Could this be a <strong>lookup table</strong> instead?”</blockquote><p><strong>Chances are… yes.</strong></p><p>And your future self will thank you (possibly with cookies 🍪).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c85f4f2487d3" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/map-vs-switch-ifs-in-typescript-cleaner-code-faster-lookups-c85f4f2487d3">Map vs Switch &amp; Ifs in TypeScript: Cleaner Code &amp; Faster Lookups</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create an Application-Wide State Management System with Signals in Angular Version 20]]></title>
            <link>https://medium.com/@trmanolis/how-to-create-an-application-wide-state-management-system-with-signals-in-angular-version-20-2313553434af?source=rss-bbd94528d352------2</link>
            <guid isPermaLink="false">https://medium.com/p/2313553434af</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[signals-features]]></category>
            <category><![CDATA[angular-signals]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Manolis Xhani Trungu]]></dc:creator>
            <pubDate>Wed, 13 Aug 2025 08:01:34 GMT</pubDate>
            <atom:updated>2025-08-13T08:07:39.590Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Learn how to build an efficient, reactive application-wide state management system using signals in Angular 20 — covering setup, best practices, and real-world examples.</em></p><figure><img alt="Gemini generated image (signals state management)" src="https://cdn-images-1.medium.com/max/1024/1*O5tAcyi5SKGeQnBQlS6KBA.png" /><figcaption>Gemini generated image (Signals state management)</figcaption></figure><h3>Introduction to State Management in Angular 20</h3><p>Angular 20 introduces built-in <strong>reactive signals</strong>, enabling developers to maintain and propagate application state much more intuitively. By leveraging signals, you can create a clean, performant global state system without the complexity or boilerplate of RxJS or NgRx redux patterns. Signals offer <strong>reduced cognitive overhead</strong>, <strong>fine-grained reactivity</strong>, and <strong>optimized change detection</strong>.</p><h3>Understanding Signals: Core Concepts and Terminology</h3><h4>What Are Signals?</h4><p>Signals are reactive primitives that hold state and propagate change notifications automatically. They’re easily observed by components, enabling UI updates whenever underlying data shifts.</p><h4>Difference Between Signals and RxJS or NgRx</h4><p>While RxJS affords streams and functional reactive programming, signals bring <strong>direct, synchronous reactivity</strong>. NgRx offers structure via actions, reducers, and effects — but adds verbosity. Signals let you co-locate state and updates more naturally.</p><h3>Setting Up Signals in Your Angular 20 Project</h3><h4>Installing and Configuring Angular Signals</h4><p>Ensure you’re using Angular 20 or later — signals are included in @angular/core. Create a new service to house your state signals.</p><h4>Creating a Global State Service with Signals</h4><p>Define your state as signals inside an injectable service. For instance, use signal&lt;T&gt;(initialValue) to initialize, and use functions like set, update, or mutate to change state.</p><pre>@Injectable({ providedIn: &#39;root&#39; })<br>export class AppStateService {<br>  count = signal&lt;number&gt;(0);<br>  setCount(newCount: number) {<br>    this.count.set(newCount);<br>  }<br>}</pre><p>You can also initialize signals holding objects or arrays, with proper typing for TypeScript safety.</p><h4>TypeScript Typings and Safety in Signal-Based State</h4><p>Using interfaces ensures structure. For example:</p><pre>interface AuthState {<br>  isLoggedIn: boolean;<br>  user?: UserProfile;<br>}</pre><p>Signals for auth state:</p><pre>authState = signal&lt;AuthState&gt;({ isLoggedIn: false });</pre><p>Update immutably for clarity:</p><pre>this.authState.update(state =&gt; ({ ...state, isLoggedIn: true, user }));</pre><h3>Using the State Service in Your Angular App</h3><h4>Consuming Signals in Components or Directives</h4><p>In your component:</p><pre>@Component({ …, standalone: true })<br>export class AppComponent {<br>  constructor(public appState: AppStateService) {}<br>}</pre><p>Then use built-in Angular template syntax:</p><pre>&lt;button (click)=&quot;appState.setCount(appState.count() + 1)&quot;&gt;<br>  Increase ({{ appState.count() }})<br>&lt;/button&gt;</pre><p>This ensures reactive updates with minimal code.</p><h4>Updating State from Events and Effects</h4><p>For async calls or effects, update signals in callback or async/await. Keep logic centralized in your state service for clean separation.</p><h3>Advanced Patterns &amp; Best Practices</h3><h4>Derived Signals and Computed Values</h4><p>Use computed to derive values:</p><pre>isAdult = computed(() =&gt; this.userState.user?.age &gt;= 18);</pre><p>These re-calculate only when base signals change.</p><h4>Performance Optimization with Signals</h4><p>Reactive change detection avoids Angular’s zone overhead. Signals can be used with OnPush and optimized detection strategies.</p><h4>Testing Signal-Based State Services</h4><p>Test signals with Jasmine or Jest:</p><pre>it(&#39;should update count&#39;, () =&gt; {<br>  service.setCount(5);<br>  expect(service.count()).toBe(5);<br>});</pre><figure><img alt="Angular state management with signals example" src="https://cdn-images-1.medium.com/max/1024/1*TTVIyh27Mfn473NfsGp5-A.png" /><figcaption>ChatGPT generated image about the example above</figcaption></figure><h3>Real-World Example: Building a User Auth State Service</h3><pre>interface AuthState { isLoggedIn: boolean; user?: User; }<br><br>@Injectable({ providedIn: &#39;root&#39; })<br>export class AuthService {<br>  authState = signal&lt;AuthState&gt;({ isLoggedIn: false });<br>  login(user: User) {<br>    this.authState.update(s =&gt; ({ ...s, isLoggedIn: true, user }));<br>  }<br>  logout() {<br>    this.authState.set({ isLoggedIn: false });<br>  }<br>}</pre><p>In your components, bind accordingly to adjust UI based on authState().isLoggedIn.</p><p><em>“The above example is a very simplified, and definitely not production ready code</em>”</p><figure><img alt="Sequence diagram of the real-world example" src="https://cdn-images-1.medium.com/max/1024/1*P2ZRpLz2F8c9zIBiUThVOw.png" /><figcaption>Sequence diagram</figcaption></figure><p>We can also expand a little bit and have a more complex example of this Authorization Service with signals.</p><pre>import { Injectable, computed, signal } from &#39;@angular/core&#39;;<br><br>interface User {<br>  id: number;<br>  name: string;<br>  role: &#39;admin&#39; | &#39;user&#39;;<br>}<br><br>interface AuthState {<br>  isLoggedIn: boolean;<br>  user?: User;<br>  token?: string;<br>}<br><br>@Injectable({ providedIn: &#39;root&#39; })<br>export class AuthService {<br>  // Base authentication state<br>  private _authState = signal&lt;AuthState&gt;({ isLoggedIn: false });<br><br>  // Derived signals<br>  isAuthenticated = computed(() =&gt; this._authState().isLoggedIn);<br>  userRole = computed(() =&gt; this._authState().user?.role ?? &#39;guest&#39;);<br><br>  // Additional UI state signals<br>  isLoading = signal(false);<br>  errorMessage = signal&lt;string | null&gt;(null);<br><br>  constructor() {<br>    // Attempt auto-login from localStorage on service init<br>    const storedToken = localStorage.getItem(&#39;auth_token&#39;);<br>    const storedUser = localStorage.getItem(&#39;auth_user&#39;);<br><br>    if (storedToken &amp;&amp; storedUser) {<br>      this._authState.set({<br>        isLoggedIn: true,<br>        token: storedToken,<br>        user: JSON.parse(storedUser),<br>      });<br>    }<br>  }<br><br>  async login(username: string, password: string) {<br>    this.isLoading.set(true);<br>    this.errorMessage.set(null);<br><br>    try {<br>      // Simulated API call delay<br>      await new Promise(resolve =&gt; setTimeout(resolve, 1000));<br><br>      // Fake API response<br>      const fakeUser: User = {<br>        id: 1,<br>        name: username,<br>        role: username === &#39;admin&#39; ? &#39;admin&#39; : &#39;user&#39;,<br>      };<br>      const fakeToken = &#39;mock-jwt-token&#39;;<br><br>      // Update state<br>      this._authState.set({<br>        isLoggedIn: true,<br>        user: fakeUser,<br>        token: fakeToken,<br>      });<br><br>      // Persist data<br>      localStorage.setItem(&#39;auth_token&#39;, fakeToken);<br>      localStorage.setItem(&#39;auth_user&#39;, JSON.stringify(fakeUser));<br>    } catch (err) {<br>      this.errorMessage.set(&#39;Login failed. Please try again.&#39;);<br>    } finally {<br>      this.isLoading.set(false);<br>    }<br>  }<br><br>  logout() {<br>    this._authState.set({ isLoggedIn: false });<br>    localStorage.removeItem(&#39;auth_token&#39;);<br>    localStorage.removeItem(&#39;auth_user&#39;);<br>  }<br><br>  get authState() {<br>    return this._authState;<br>  }<br>}</pre><pre>@Component({<br>  selector: &#39;app-header&#39;,<br>  template: `<br>    &lt;nav&gt;<br>      &lt;span *ngIf=&quot;authService.isAuthenticated()&quot;&gt;Welcome, {{ authService.authState().user?.name }}&lt;/span&gt;<br>      &lt;span *ngIf=&quot;!authService.isAuthenticated()&quot;&gt;Please log in&lt;/span&gt;<br>      &lt;button *ngIf=&quot;authService.isAuthenticated()&quot; (click)=&quot;authService.logout()&quot;&gt;Logout&lt;/button&gt;<br>    &lt;/nav&gt;<br>  `,<br>  standalone: true<br>})<br>export class HeaderComponent {<br>  constructor(public authService: AuthService) {}<br>}</pre><h3>What’s New in This Example</h3><ol><li><strong>Persistent login</strong>: Automatically logs in the user if a valid token is found in localStorage.</li><li><strong>Derived signals</strong>: No need to compute isAuthenticated or userRole manually in each component.</li><li><strong>Loading state</strong>: Components can show spinners during login.</li><li><strong>Error handling</strong>: Displays user-friendly error messages on login failure.</li><li><strong>Role-based UI</strong>: Components can adapt based on userRole without extra logic.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*16bvdbywTXnqRvB29PxTgA.png" /><figcaption>Sequence Diagram with the flow for the more complex example</figcaption></figure><h3>FAQ: Common Questions About Signals and State Management</h3><ul><li><strong>What are the advantages of signals over NgRx in Angular 20?</strong></li><li>Signals require <strong>less boilerplate</strong>, are more intuitive, and offer <strong>fine-grained reactivity</strong>.</li><li><strong>Can signals replace RxJS completely?</strong></li><li>Not always — RxJS is still ideal for complex streams and operators. Signals complement simpler use cases.</li><li><strong>How to avoid performance pitfalls with global signals?</strong></li><li>Use computed, avoid unnecessary updates, and combine signals with OnPush detection.</li><li><strong>Is signal-based state management scalable for large apps?</strong></li><li>Yes, especially when signals are modularized by feature and structured predictably.</li><li><strong>Migration strategies from NgRx or BehaviorSubjects?</strong></li><li>Gradually refactor stores to signal services; abstract selectors into computed signals.</li><li><strong>Can I mix signals with existing reactive state management?</strong></li><li>Absolutely — signals can wrap or consume RxJS streams or vice versa.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2313553434af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 Life-Changing Ways to Achieve Self Empowering and Unlock Your True Potential]]></title>
            <link>https://medium.com/@trmanolis/10-life-changing-ways-to-achieve-self-empowering-and-unlock-your-true-potential-40841d256c4a?source=rss-bbd94528d352------2</link>
            <guid isPermaLink="false">https://medium.com/p/40841d256c4a</guid>
            <category><![CDATA[mindfulness]]></category>
            <category><![CDATA[mental-health]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[self]]></category>
            <dc:creator><![CDATA[Manolis Xhani Trungu]]></dc:creator>
            <pubDate>Sat, 09 Aug 2025 03:39:22 GMT</pubDate>
            <atom:updated>2025-08-09T03:39:22.120Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IRd_etJEzrkBol8urEMj7w.png" /><figcaption>Unlock you full potential</figcaption></figure><h3>Introduction: The Power of Self Empowering</h3><p>Self empowering is the art of taking control of your life, owning your choices, and building the confidence to live authentically. In a world full of distractions, societal expectations, and self-doubt, learning how to empower yourself is one of the most valuable investments you can make in your personal growth.</p><p>It’s not just about feeling confident—it’s about having the skills, mindset, and resilience to create the life you want.</p><h3>What Does Self Empowering Really Mean?</h3><ul><li>Definition and Core Principles</li></ul><p>At its core, self empowering means taking responsibility for your actions, embracing your strengths, and actively working to improve your weaknesses. It’s a mindset shift that transforms you from feeling powerless to becoming the driver of your own destiny.</p><ul><li>Why Self Empowerment Matters in Today’s World</li></ul><p>We live in a fast-paced, competitive environment where external validation often drives self-worth. Self empowerment gives you the freedom to define success on your own terms, making you less dependent on others for approval and more resilient against setbacks.</p><h3>The Psychological Foundation of Self Empowering</h3><ul><li>The Role of Mindset and Belief Systems</li></ul><p>Your beliefs shape your reality. A growth mindset—believing you can learn, improve, and adapt—is the foundation of empowerment.</p><ul><li>Overcoming Limiting Beliefs</li></ul><p>Limiting beliefs are mental barriers that keep you from taking action. By challenging these beliefs and replacing them with positive affirmations, you create space for personal growth.</p><h3>10 Proven Strategies to Achieve Self Empowering</h3><h4>1. Set Clear, Achievable Goals</h4><p>Clarity is power. Setting SMART goals (Specific, Measurable, Achievable, Relevant, Time-bound) helps you stay focused and motivated.</p><h4>2. Build Self-Awareness Through Reflection</h4><p>Journaling and meditation can help you understand your strengths, weaknesses, and emotional triggers.</p><h4>3. Develop Emotional Intelligence</h4><p>Learn to manage your emotions and understand others’ feelings to strengthen relationships.</p><h4>4. Master the Art of Positive Self-Talk</h4><p>The way you speak to yourself shapes your confidence. Replace self-criticism with encouragement.</p><h4>5. Cultivate Resilience in the Face of Challenges</h4><p>See setbacks as lessons, not failures. Every obstacle is an opportunity to grow stronger.</p><h4>6. Take Responsibility for Your Actions</h4><p>Owning your choices builds integrity and self-respect.</p><h4>7. Surround Yourself with Positive Influences</h4><p>Your environment shapes your mindset. Choose relationships that uplift and inspire you.</p><h4>8. Learn New Skills and Keep Growing</h4><p>Personal growth is a lifelong process. Keep learning to boost your adaptability.</p><h4>9. Practice Gratitude Daily</h4><p>Gratitude shifts your focus from what’s missing to what’s abundant in your life.</p><h4>10. Celebrate Your Wins, Big and Small</h4><p>Acknowledging progress boosts motivation and self-worth.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3hHz__udB4BvceEBqGFSw.png" /><figcaption>10 self empowering strategies</figcaption></figure><h3>Self Empowering in Relationships Setting Healthy Boundaries</h3><h4>Setting Healthy Boundaries</h4><p>Boundaries protect your emotional and mental well-being.</p><h4>Communicating with Confidence</h4><p>Speak clearly, assertively, and respectfully to express your needs.</p><h3>How to Overcome Common Obstacles to Self Empowering</h3><ul><li>Fear of Failure</li></ul><p>Redefine failure as feedback.</p><ul><li>Negative Self-Image</li></ul><p>Challenge self-critical thoughts with evidence of your worth.</p><ul><li>Toxic Environments</li></ul><p>Limit exposure to negativity and create a supportive space.</p><h3>The Long-Term Benefits of Self Empowering</h3><ul><li>Career Growth and Leadership</li></ul><p>Empowered individuals often excel in leadership roles because they inspire trust and take initiative.</p><ul><li>Emotional and Mental Well-Being</li></ul><p>Self empowering promotes confidence, resilience, and a sense of purpose.</p><h3>Frequently Asked Questions About Self Empowering</h3><p>Q1: What’s the first step to self empowering?<br>A: Start by identifying your values and setting small, achievable goals.</p><p>Q2: Can self empowering help in career growth?<br>A: Absolutely. Empowered individuals are proactive, confident, and adaptable—key traits for career success.</p><p>Q3: How long does it take to feel empowered?<br>A: It varies, but consistent practice of empowering habits can show results in weeks or months.</p><p>Q4: Is self empowering the same as self-confidence?<br>A: Not exactly. Self-confidence is a feeling, while self empowering is a mindset and ongoing practice.</p><p>Q5: Can anyone become self empowered?<br>A: Yes, with dedication, self-awareness, and persistence, anyone can build empowerment skills.</p><p>Q6: How does gratitude help in self empowering?<br>A: Gratitude rewires your brain to focus on positivity, boosting your sense of control and optimism.</p><h3>Conclusion: Your Journey Starts Now</h3><p>Self empowering is a journey, not a one-time event. By taking consistent action, embracing challenges, and nurturing a growth mindset, you can create a life that’s driven by your own values and ambitions. The power is in your hands—start today.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40841d256c4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gems inside Angular]]></title>
            <link>https://medium.com/@trmanolis/gems-inside-angular-b7bad8a56b49?source=rss-bbd94528d352------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7bad8a56b49</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[angular-tips]]></category>
            <category><![CDATA[angular-tips-and-tricks]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-4]]></category>
            <dc:creator><![CDATA[Manolis Xhani Trungu]]></dc:creator>
            <pubDate>Fri, 18 Jul 2025 12:14:20 GMT</pubDate>
            <atom:updated>2025-09-14T22:42:54.546Z</atom:updated>
            <content:encoded><![CDATA[<h3>A nice Gem inside Angular</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a-ylu7s_Qj4JF35zFZeRZg.png" /><figcaption>Angular View Providers logo with provider name</figcaption></figure><h3>What Are viewProviders in Angular?</h3><p>In Angular, <strong>providers</strong> define how to supply a dependency to a component and its children. When you register a service in the providers array of a component, Angular makes that service available to:</p><ul><li>The component itself</li><li>Its template</li><li>Any child components</li><li>And even content projected using &lt;ng-content&gt;</li></ul><p>However, Angular also gives you a more restrictive option: <strong>viewProviders</strong>.</p><h3>What Is viewProviders?</h3><p>The viewProviders array works like providers, but with <strong>one key difference</strong>: it limits the visibility of the service to the <strong>component’s view only</strong>.</p><p>This means:</p><ul><li>The service is accessible to the component and elements <strong>declared in its own template</strong></li><li>It is <strong>not accessible</strong> to content projected from outside (via &lt;ng-content&gt;)</li><li>It is also <strong>not available</strong> to external child components rendered via projection</li></ul><p>In short: viewProviders allow you to encapsulate a service <strong>strictly within the component’s own view</strong>, preventing it from being accessed by nested or projected components.</p><h3>providers vs viewProviders Scope</h3><p>Here’s the difference:</p><ul><li><strong>providers</strong>: Service is visible everywhere within the component, including projected content.</li><li><strong>viewProviders</strong>: Service is visible <strong>only</strong> to the component’s view—not to projected content.</li></ul><p>This may seem like a subtle difference, but it’s <strong>crucial</strong> for creating reusable, predictable components that don’t accidentally expose internal services to outside templates.</p><h3>Use Case: Modal with Projected Content</h3><p>Let’s see this in action with a ModalComponent.</p><p>Say you’re building a modal component that controls its own visibility (open/close), and you want to encapsulate that logic in a ModalStateService.</p><p>But — here’s the twist — you allow arbitrary content to be projected inside the modal (via &lt;ng-content&gt;), and you don’t want that projected content to mess with the modal’s internal state.</p><h3>ModalComponent using viewProviders</h3><pre>@Component({<br>  selector: &#39;app-modal&#39;,<br>  template: `<br>    &lt;section class=&quot;modal&quot; *ngIf=&quot;!state.isClosed()&quot;&gt;<br>      &lt;header class=&quot;modal-header&quot;&gt;<br>        &lt;h2&gt;{{ title() }}&lt;/h2&gt;<br>        &lt;button (click)=&quot;close()&quot;&gt;X&lt;/button&gt;<br>      &lt;/header&gt;<br>      &lt;div class=&quot;modal-body&quot;&gt;<br>        &lt;ng-content&gt;&lt;/ng-content&gt;<br>      &lt;/div&gt;<br>    &lt;/section&gt;<br>  `,<br>  styleUrls: [&#39;./modal.component.scss&#39;],<br>  viewProviders: [ModalStateService],<br>})<br>export class ModalComponent {<br>  private readonly state = inject(ModalStateService);<br><br>title = input.required&lt;string&gt;();<br>  close() {<br>    this.state.close();<br>  }<br>}</pre><h3>ModalStateService</h3><pre>@Injectable()<br>export class ModalStateService {<br>  private readonly _closed = signal(false);<br>  readonly isClosed = this._closed.asReadonly();<br><br>  close(): void {<br>    this._closed.set(true);<br>  }<br>  open(): void {<br>    this._closed.set(false);<br>  }<br>}</pre><h3>Projected Content Attempting to Use the Service</h3><pre>@Component({<br>  selector: &#39;app-modal-body&#39;,<br>  template: `<br>    &lt;p&gt;This is custom content injected into the modal.&lt;/p&gt;<br>    &lt;button (click)=&quot;attemptClose()&quot;&gt;Try Close Modal&lt;/button&gt;<br>  `,<br>})<br>export class ModalBodyComponent {<br>  // ❌ This will throw an error if `ModalStateService` is in `viewProviders`<br>  private readonly state = inject(ModalStateService);<br><br>  attemptClose() {<br>    this.state.close();<br>  }<br>}</pre><h3>Usage</h3><pre>&lt;app-modal title=&quot;Example Modal&quot;&gt;<br>  &lt;app-modal-body&gt;&lt;/app-modal-body&gt;<br>&lt;/app-modal&gt;</pre><h3>Why It Matters</h3><p>In the example above:</p><ul><li>The ModalStateService is scoped only to the view of ModalComponent</li><li>The projected ModalBodyComponent <strong>cannot inject or modify</strong> the modal’s internal state</li></ul><p>Had we used the broader providers array, ModalBodyComponent would have been able to inject the state service—possibly altering the modal’s behavior unexpectedly.</p><p>This kind of tight coupling is dangerous, especially in component libraries or reusable UI systems. By using viewProviders, we maintain <strong>encapsulation</strong>, reduce side effects, and build <strong>predictable components</strong>.</p><h3>Summary</h3><ul><li>Use providers if you want a service to be accessible by the component, its children, and any projected content.</li><li>Use viewProviders to restrict the service to the component’s own view.</li><li>This technique is essential when building components that are meant to be <strong>modular, isolated, and secure</strong> from external interference.</li></ul><blockquote><em>Think of </em><em>viewProviders as your component’s private state locker—it’s safe, secure, and invisible to outsiders.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7bad8a56b49" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>