<?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 Ricky Lopes on Medium]]></title>
        <description><![CDATA[Stories by Ricky Lopes on Medium]]></description>
        <link>https://medium.com/@monsieur_ricky?source=rss-6d06bc8a89e2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*oj2qpmbozqWi22vb</url>
            <title>Stories by Ricky Lopes on Medium</title>
            <link>https://medium.com/@monsieur_ricky?source=rss-6d06bc8a89e2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 01:16:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@monsieur_ricky/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[Going Zoneless: Why Your Angular ErrorHandler Went Silent — and How to Fix It]]></title>
            <link>https://medium.com/@monsieur_ricky/going-zoneless-why-your-angular-errorhandler-went-silent-and-how-to-fix-it-eb8edd038a2e?source=rss-6d06bc8a89e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb8edd038a2e</guid>
            <category><![CDATA[angular-zoneless]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Ricky Lopes]]></dc:creator>
            <pubDate>Mon, 27 Oct 2025 07:32:18 GMT</pubDate>
            <atom:updated>2025-10-27T07:32:18.221Z</atom:updated>
            <content:encoded><![CDATA[<h3>Going Zoneless: Why Your Angular ErrorHandler Went Silent — and How to Fix It</h3><figure><img alt="Cover image with the Angular logo and the title “Going Zoneless: Why Your Angular ErrorHandler Went Silent — and How to Fix It”" src="https://cdn-images-1.medium.com/max/1024/1*pgieK67ryA9EehzbcsQSZA.png" /></figure><p>With the Angular team officially promoting the zoneless API to stable in v20.2, many developers are now migrating to <a href="https://angular.dev/api/core/provideZonelessChangeDetection">provideZonelessChangeDetection()</a> to improve performance and reduce initial bundle size. However, this migration introduces a critical change that can silently &quot;break&quot; global error monitoring.</p><p>This issue often surfaces post-deployment — a scenario I experienced firsthand. User-reported errors no longer being captured by external logging services, and UI error messages handled by Angular’s ErrorHandler fail to appear. Local debugging exposed errors in the browser console, indicating that certain asynchronous exceptions were bypassing the global error handling flow.</p><p>This occurs because the application’s custom ErrorHandler, which previously intercepted all synchronous and asynchronous errors, suddenly stops receiving errors from asynchronous operations (like Promises, Observables, or setTimeout).</p><p>This behaviour is not a bug, but a fundamental change in execution. The ErrorHandler is still functional, but it has lost its automatic error-forwarding mechanism, which was a feature of zone.js, not Angular&#39;s core.</p><p>This article will provide a technical explanation for this behaviour and detail the modern, official solution to restore comprehensive global error handling in a zoneless Angular application.</p><h3>How zone.js Performed Global Error Interception</h3><p>With zone.js, Angular’s global error handling is comprehensive. This capability is not part of Angular’s <a href="https://angular.dev/api/core/ErrorHandler">ErrorHandler</a> itself, but a core feature of zone.js.</p><p>Here’s a breakdown of the technical process:</p><ol><li><strong>Patches Asynchronous APIs:</strong> zone.js &quot;monkey-patches&quot; (i.e., overwrites) browser-native asynchronous functions like setTimeout, Promise, and event listeners.</li><li><strong>Creates an Execution Context:</strong> When you run an async task, it is wrapped in a “zone”, which is an execution context that can monitor the task’s lifecycle.</li><li><strong>Intercepts Unhandled Errors:</strong> If a Promise is rejected or an error is thrown in a setTimeout without a local catch block, the zone.js patch intercepts it before it reaches the browser&#39;s global scope.</li><li><strong>Forwards Errors to </strong><strong>NgZone:</strong> Angular&#39;s NgZone service, which is built on zone.js, listens for these intercepted errors and programmatically forwards them to your application&#39;s ErrorHandler.</li></ol><p>This is why ErrorHandler, or any custom handler, works so well. It’s receiving a steady stream of errors from NgZone without us needing to add try...catch blocks to all your asynchronous code.</p><h3>Why Errors Might Get Uncaught With Zoneless</h3><p>When we use provideZonelessChangeDetection(), we configure Angular to operate without zone.js as its change detection scheduler. In some cases, we can even completely remove this package from our project&#39;s dependencies (<a href="https://angular.dev/guide/zoneless#removing-zonejs">as the Angular team recommends</a>). Consequently, without zone.js loaded, no browser-native asynchronous APIs are “monkey-patched”.</p><p>Now, when an unhandled async error occurs, it follows the standard browser behaviour:</p><ul><li>A Promise rejection becomes a global <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/unhandledrejection_event">unhandledrejection</a> event.</li><li>A setTimeout or other script error becomes a global <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error">error</a> event.</li></ul><p>Angular’s ErrorHandler does not natively listen for these browser-level events. It will still catch errors that happen synchronously within Angular&#39;s own execution (like a bad template binding or a DI failure), but it loses visibility into asynchronous errors that it did not initiate.</p><h3>The Solution: Re-Establishing Global Listeners</h3><p>Since zone.js is no longer patching and forwarding errors, we must manually listen for these global browser events and forward them to Angular&#39;s ErrorHandler.</p><p>While we could do this manually with an APP_INITIALIZER token, the Angular team recognised this exact problem and provided a clean official API to solve it: <a href="https://angular.dev/api/core/provideBrowserGlobalErrorListeners#">provideBrowserGlobalErrorListeners()</a>.</p><p>This function does exactly what we need: it sets up the listeners for unhandledrejection and error, and forwards those errors to our ErrorHandler.</p><h4>The Technical Implementation</h4><p>The solution to “revive” our previous working custom ErrorHandler is quite simple and strait forward, we just need to add the provideBrowserGlobalErrorListeners() to the project&#39;s bootstrapApplication() providers:</p><pre><br>import {<br>  ErrorHandler,<br>  bootstrapApplication<br>  provideZonelessChangeDetection,<br>  provideBrowserGlobalErrorListeners, // &lt;-- Import the new provider<br>} from &#39;@angular/core&#39;;<br>import { AppComponent } from &#39;./app/app.component&#39;;<br>import { MyCustomErrorHandler } from &#39;./my-custom-error-handler.service&#39;; // &lt;-- Custom handler<br><br>bootstrapApplication(AppComponent, {<br>  providers: [<br>    provideZonelessChangeDetection(),<br>    // Custom handler as the main ErrorHandler<br>    {<br>      provide: ErrorHandler,<br>      useClass: MyCustomErrorHandler,<br>    },<br>    // Add the official global listener<br>    // This connects the browser&#39;s global errors to the ErrorHandler<br>    provideBrowserGlobalErrorListeners(),<br>  ]<br>}).catch((err) =&gt; console.error(err));</pre><p>With this, our application will now catch all global asynchronous errors again 🎉</p><p><strong>One important point to note:</strong> from Angular v20, this provider is automatically included when you create a new project using the CLI.</p><h3>Conclusion</h3><p>The issue of an inactive ErrorHandler in a zoneless application is a direct consequence of removing zone.js. We&#39;ve established that it’s role was not just to trigger change detection, but also to act as a comprehensive interception mechanism for asynchronous tasks. Its “monkey-patching” of browser APIs provided a &quot;catch-all&quot; that automatically forwarded unhandled rejections and script errors to Angular&#39;s ErrorHandler. When we remove zone.js, we remove this implicit error-forwarding bridge.</p><p>We solved this by explicitly re-establishing that connection. By implementing the official provideBrowserGlobalErrorListeners() provider, we manually subscribe to the browser&#39;s global error and unhandledrejection events.</p><p>This experience encapsulates the core trade-off of going zoneless: we exchange the implicit conveniences of zone.js for explicit control and performance. While we benefit from a smaller bundle and fewer change detection cycles, we become responsible for tasks that were once “automatic”.</p><h4>References for Further Reading</h4><ul><li><a href="https://github.com/angular/angular/issues/63704"><strong>Angular GitHub Issue #63704</strong></a>: Community discussion reporting that HttpClient errors are uncaught in zoneless, confirming the problem.</li><li><a href="http://providebrowserglobalerrorlisteners/"><strong>Angular Official Docs: </strong></a><a href="http://providebrowserglobalerrorlisteners/"><strong>provideBrowserGlobalErrorListeners()</strong></a>: The official API documentation for the solution.</li><li><a href="https://angular.dev/best-practices/error-handling"><strong>Angular Official Docs: Unhandled errors</strong></a>: The high-level guide to error handling in Angular.</li><li><a href="https://www.google.com/search?q=%5Bhttps://developer.mozilla.org/en-US/docs/Web/API/Window/unhandledrejection_event%5D(https://developer.mozilla.org/en-US/docs/Web/API/Window/unhandledrejection_event)"><strong>MDN Web Docs: </strong></a><a href="https://www.google.com/search?q=%5Bhttps://developer.mozilla.org/en-US/docs/Web/API/Window/unhandledrejection_event%5D(https://developer.mozilla.org/en-US/docs/Web/API/Window/unhandledrejection_event)"><strong>unhandledrejection event</strong></a>: Learn about the underlying browser event you are now handling.</li><li><a href="https://www.angular.courses/caniuse/features?search=provideBrowserGlobalErrorListeners"><strong>Angular Can I Use — provideBrowserGlobalErrorListeners:</strong></a> Explore available Angular features and their compatibility across versions.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb8edd038a2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Accessible Web Applications with Angular: Insights from Angular Global Summit 25]]></title>
            <link>https://medium.com/@monsieur_ricky/creating-accessible-web-applications-with-angular-insights-from-angular-global-summit-25-7378fa067d5e?source=rss-6d06bc8a89e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/7378fa067d5e</guid>
            <category><![CDATA[a11y]]></category>
            <category><![CDATA[accessibility]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-accessibility]]></category>
            <dc:creator><![CDATA[Ricky Lopes]]></dc:creator>
            <pubDate>Sat, 10 May 2025 13:22:06 GMT</pubDate>
            <atom:updated>2025-05-10T13:22:06.532Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qtvosxSEgeGRyroqOt-xcA.jpeg" /></figure><p>At this year’s <a href="https://event.geekle.us/angular">Geekle Angular Global Summit</a>, I had the pleasure of speaking about “Creating Accessible Web Applications with Angular”. This article aims to recap the core concepts discussed and demonstrate how developers, especially those working with Angular, can build more inclusive frontend applications.</p><h3><strong>What is Web Accessibility?</strong></h3><p>The digital world should be open to all, and Web accessibility (often abbreviated as a11y) is the practice of <strong>ensuring that websites and applications are designed and developed so that people with disabilities can use them effectively</strong>.</p><p>This isn’t just a niche concern; globally, around <a href="https://www.who.int/health-topics/disability#tab=tab_1">1.3 billion people live with some form of disability</a>, and in the EU alone, <a href="https://www.consilium.europa.eu/en/infographics/disability-eu-facts-figures/">this figure stands at approximately 101 million</a>. Despite the clear need, <a href="https://webaim.org/projects/million/">a staggering 94.8% of websites have Web Content Accessibility Guidelines (WCAG) failures</a>, highlighting a significant gap in creating truly inclusive online experiences.</p><h3>Understanding the Core Principles of Web Accessibility</h3><p>Before diving into Angular specifics, it’s essential to grasp the fundamental practices that underpin Web Accessibility:</p><ul><li><strong>Semantic HTML:</strong> Using HTML elements according to their meaning (e.g., &lt;nav&gt; for navigation, &lt;button&gt; for buttons) provides inherent structure and accessibility.</li><li><strong>Keyboard Navigation:</strong> All interactive elements must be operable via a keyboard, ensuring users who cannot use a mouse can still navigate and interact with the site.</li><li><strong>Alternative Text for Images:</strong> Images should have descriptive alt text (alt attribute) so that screen readers can convey their meaning to visually impaired users. For purely decorative images, an empty alt attribute (alt=&quot;&quot;) is appropriate.</li><li><strong>Captions for Videos:</strong> Videos should include captions or transcripts for users with hearing impairments.</li><li><strong>Correct Color Contrast:</strong> Sufficient contrast between text and background colors is vital for users with low vision or color blindness.</li><li><strong>ARIA Attributes:</strong> Accessible Rich Internet Applications (ARIA) attributes can be used to enhance the accessibility of web content, especially for dynamic content and complex UI controls, by providing additional information to assistive technologies.</li></ul><p>Adhering to these fundamental principles lays the groundwork for a more universally usable web.</p><h3><strong>The Challenge with Single Page Applications (SPAs)</strong></h3><p>My presentation mentioned, perhaps surprisingly to some, “Avoid using SPAs” as a consideration for inclusive websites. While SPAs, common in frameworks like Angular (or React, Vue, etc.), offer rich, dynamic user experiences, they can introduce unique accessibility hurdles if not developed mindfully. Here’s a brief explanation why:</p><ul><li><strong>Dynamic Content Updates:</strong> In SPAs, content often changes without a full page reload. Assistive technologies like screen readers might not automatically detect or announce these changes. This can leave users unaware of new information appearing on the page or unsure if their actions have had an effect.</li><li><strong>Focus Management:</strong> When views change or new content is loaded dynamically in an SPA, the keyboard focus might not shift appropriately. Users relying on keyboard navigation can find their focus lost, or it might remain on an element that’s no longer relevant or even visible, leading to confusion and an inability to interact with the new content.</li><li><strong>Routing and Page Titles:</strong> SPAs handle navigation (routing) on the client-side. This means the browser doesn’t perform a traditional page load. Consequently, page titles might not update automatically, and the browser’s back/forward buttons might not behave as users expect. For screen reader users, the page title is a key piece of information that orients them to new content; if it doesn’t change, they may not realize the “page” has changed.</li><li><strong>Semantic Information for Assistive Technologies:</strong> Because SPAs heavily rely on JavaScript to render UI components, developers must be diligent in ensuring these components have the correct semantic HTML structure and ARIA attributes. Without these, complex custom controls or dynamically generated content can be opaque to assistive technologies.</li></ul><p>However, it’s crucial to understand that these challenges are not impossible to overcome. Modern JavaScript frameworks, including Angular with its <a href="https://material.angular.dev/cdk/a11y/overview">Component Development Kit (CDK)</a>, provide tools and techniques to address these issues effectively, as we’ll explore in the next chapters.</p><h3>Essential Tools for Accessibility Testing</h3><p>Building accessible applications is an ongoing process that requires regular testing. Fortunately, numerous tools can assist in identifying and resolving accessibility issues:</p><ul><li><strong>Browser Developer Tools:</strong> Google Lighthouse (integrated into Chrome DevTools), <a href="https://www.deque.com/axe/devtools/web-accessibility/">axe DevTools</a> (browser extension), and <a href="https://wave.webaim.org/">WAVE</a> (Web Accessibility Evaluation Tool, browser extension) are excellent for automated accessibility checks and identifying common WCAG violations.</li><li><strong>Linters:</strong> Integrating accessibility checks into your development workflow with tools like <a href="https://github.com/angular-eslint/angular-eslint">Angular ESLint</a> or <a href="https://docs.sonarsource.com/sonarqube-for-ide/vs-code/">SonarQube</a> can help catch issues early.</li><li><strong>Screen Readers:</strong> Testing with actual assistive technologies is crucial. Popular screen readers include Windows Narrator (available in Windows OS), Apple VoiceOver (built into macOS and iOS), <a href="https://www.nvaccess.org/">NVDA </a>(NonVisual Desktop Access — free for Windows), and <a href="https://www.freedomscientific.com/products/software/jaws/">JAWS</a> (Job Access With Speech — paid for Windows).</li></ul><h3>Leveraging Angular for Accessible Applications</h3><p>Angular, as a comprehensive frontend framework, provides developers with powerful tools to build accessible applications. A key resource in this domain is the <a href="https://material.angular.dev/cdk/a11y/overview"><strong>Angular Material Component Development Kit (CDK)</strong></a>, which includes a dedicated accessibility package (@angular/cdk/a11y). This toolkit offers several utilities to help developers address common accessibility concerns:</p><h4><strong>Focus Management:</strong></h4><ul><li>FocusTrap: The cdkTrapFocus directive is invaluable for modals and dialogs. It traps Tab-key focus within an element, preventing users from accidentally navigating outside the modal while it&#39;s active. This is crucial for users who rely on keyboard navigation.</li><li>FocusMonitor: This service (FocusMonitor) helps track the focus state of elements. It can detect how an element was focused (mouse, keyboard, touch, or programmatically) and can be used to apply different styles or behaviors accordingly. The CDK also provides directives like cdkMonitorElementFocus and cdkMonitorSubtreeFocus for easily monitoring an element or an entire subtree.</li></ul><h4><strong>LiveAnnouncer:</strong></h4><ul><li>The LiveAnnouncer service allows you to announce messages to screen reader users, which is particularly useful for dynamic content changes that might not be obvious, such as status updates or notifications.</li></ul><h4><strong>ListKeyManager:</strong></h4><ul><li>This utility helps manage keyboard interactions (like arrow key navigation) for list-like components such as menus, dropdowns, and list boxes, ensuring they are navigable and operable via the keyboard.</li></ul><h4><strong>Styling for High Contrast Mode:</strong></h4><ul><li>The @angular/cdk/a11y package includes SASS Mixins, like high-contrast, that allow you to define styles specifically for users who have enabled high contrast mode in their operating system. The a11y-visually-hidden SASS mixin emits the .cdk-visually-hidden CSS class, which can be used to hide elements visually while keeping them accessible to screen readers.</li></ul><p>By utilizing these CDK tools, Angular developers can significantly improve the accessibility of their applications, making them more robust and usable for a wider range of users.</p><h3>Key Takeaways for Building Inclusive Web Apps</h3><p>As summarized in the <a href="https://event.geekle.us/angular">Angular Global Summit</a> talk, creating accessible web applications involves a combination of understanding, best practices, and leveraging the right tools:</p><ul><li>Always start with <strong>Semantic HTML</strong>.</li><li>Provide <strong>realistic and descriptive alternative text</strong> for images.</li><li>Ensure <strong>proper color contrasts</strong>.</li><li>Use <strong>ARIA attributes</strong> wisely to enhance semantics where needed.</li><li>Take full advantage of <strong>Angular’s CDK accessibility tools</strong>.</li><li>Crucially, perform <strong>real testing with assistive technologies</strong> to understand the user experience from different perspectives.</li></ul><p>Web accessibility is not just a checklist, it’s a mindset and a commitment to inclusivity. By embracing these principles and tools, we, as developers, can make a significant difference in creating a web that is truly for everyone.</p><h3>Resources</h3><p>For those interested in the code examples or the full summit session, check out these links:</p><ul><li>Demo Repository: <a href="https://github.com/monsieur-ricky/angular-a11y">https://github.com/monsieur-ricky/angular-a11y</a></li><li>Angular Global Summit Video:</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fa-Ms3gNniQw%3Fstart%3D201%26feature%3Doembed%26start%3D201&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Da-Ms3gNniQw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fa-Ms3gNniQw%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/951dbc7a8000836193154431e874f5d1/href">https://medium.com/media/951dbc7a8000836193154431e874f5d1/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7378fa067d5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Components in Angular: Creating UI Elements for Cross-Framework Compatibility]]></title>
            <link>https://medium.com/@monsieur_ricky/web-components-in-angular-creating-ui-elements-for-cross-framework-compatibility-c72998782cd6?source=rss-6d06bc8a89e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c72998782cd6</guid>
            <category><![CDATA[custom-elements]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-components]]></category>
            <category><![CDATA[angular-19]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Ricky Lopes]]></dc:creator>
            <pubDate>Fri, 31 Jan 2025 18:04:56 GMT</pubDate>
            <atom:updated>2025-01-31T18:04:56.386Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6KZZSE-rTJwB86m0KBzBmA.jpeg" /></figure><p>As modern web applications are becoming increasingly complex, the need for modular, reusable, and maintainable code becomes critical. Imagine building UI components once and reusing them anywhere, regardless of the framework you choose.</p><p>Web Components offer a compelling solution, enabling developers to create encapsulated UI elements that function across frameworks.</p><p>This article explores <strong>Web Components</strong> and demonstrates how to build framework-agnostic components with <strong>Angular</strong>.</p><h3>What Are Web Components?</h3><p>Web Components provide a standard way to build reusable, encapsulated HTML elements. These elements are defined using web platform APIs and can be used in any web page or application.</p><p>They are built using the following core technologies:</p><ol><li><strong>Custom Elements</strong>: A set of JavaScript APIs that allow defining new HTML tags with encapsulated behavior.</li><li><strong>Shadow DOM</strong>: Enables the creation of encapsulated HTML and CSS for an element by attaching a separate, isolated DOM tree to it, ensuring that the element’s internal structure and styling remain independent of the main document.</li><li><strong>HTML Templates</strong>: The &lt;template&gt; and &lt;slot&gt; elements that enable creating markup templates that are not rendered until they are instantiated.</li><li><strong>ES Modules</strong>: A standardized module system for JavaScript that enable import and export of functionalities across different files.</li></ol><p>These features allow developers to write components that can be used anywhere, regardless of the frontend framework.</p><h3>Why Use Web Components?</h3><p>As web applications grow in complexity, the need for modularity, reusability, and maintainability becomes critical. Web Components address these needs by providing a standardized way to create reusable and encapsulated components. Here are some key benefits of using Web Components:</p><h4>Reusability:</h4><ul><li><strong>Cross-Project Reusability</strong>: Web Components can be reused across different projects and applications, reducing duplication of effort and ensuring consistency.</li><li><strong>Framework Agnostic</strong>: They work seamlessly with any JavaScript framework (e.g., Angular, Vue, React, etc.) or even without any framework, making them highly versatile.</li><li><strong>Micro Frontends and Modular Architecture</strong>:<strong> </strong>Organizations with multiple teams working on different frontend stacks can use Web Components to ensure a consistent UI without forcing a single framework.</li></ul><h4>Encapsulation:</h4><ul><li><strong>Shadow DOM</strong>: The Shadow DOM ensures that the styles and behavior of a component are encapsulated, preventing conflicts with other parts of the application.</li><li><strong>Isolation</strong>: Encapsulation helps in isolating the component’s logic and styling, making it easier to manage and maintain.</li></ul><h4>Interoperability:</h4><ul><li><strong>Standardized API</strong>: Web Components are based on web standards, ensuring they work across different browsers and environments.</li><li><strong>Framework Compatibility</strong>: They can be integrated into existing applications built with different frameworks, providing a unified way to manage components.</li></ul><h4>Maintainability:</h4><ul><li><strong>Modular Code</strong>: By breaking down the application into smaller, reusable components, the codebase becomes more modular and easier to maintain.</li><li><strong>Separation of Concerns</strong>: Web Components promote a clear separation of concerns, making it easier to debug and update individual parts of the application.</li></ul><h4>Future-Proofing:</h4><ul><li><strong>Web Standards</strong>: Being based on web standards, Web Components are likely to be supported for a long time, ensuring the longevity of the code.</li><li><strong>Polyfills</strong>: For older browsers, polyfills can be used to provide support, ensuring backward compatibility.</li></ul><h3>Real-World Use Cases</h3><p>How are Web Components being used in practice? These are just some of the real-world use cases of Web Components and their versatility:</p><h4>Design Systems:</h4><ul><li><strong>Consistent UI</strong>: Web Components are ideal for building design systems that ensure a consistent look and feel across different parts of the application.</li><li><strong>Themeable Components</strong>: They can be easily themed and customized to match the branding and design requirements.</li></ul><h4>Micro Frontends:</h4><ul><li><strong>Independent Deployment</strong>: Web Components can be used to build micro frontends, where different parts of the application are developed and deployed independently.</li><li><strong>Integration</strong>: They provide a way to integrate different micro frontends into a cohesive application.</li></ul><h4>Third-Party Widgets:</h4><ul><li><strong>Embeddable Components</strong>: Web Components can be used to create embeddable widgets (e.g., chat widgets, analytics widgets) that can be easily integrated into different websites.</li><li><strong>Isolation</strong>: The encapsulation provided by Web Components ensures that these widgets do not interfere with the host application.</li></ul><h3>Potential Drawbacks</h3><p>Unfortunately, it’s not all rainbows and unicorns. Despite their benefits, Web Components remain a <a href="https://medium.com/@treeder/web-components-are-the-future-f0f9f0022686"><strong>controversial</strong></a> topic in the frontend development community. I’ll try to highlight some of the reasons why:</p><ul><li><strong>Lack of Full Framework Integration: </strong>While Web Components work with most modern frameworks, they don’t integrate as deeply as native components. Features like state management and two-way data binding require additional handling.</li><li><strong>Performance Overhead: </strong>Web Components can introduce extra overhead, especially when using frameworks like Angular that already provide built-in component lifecycles and optimizations.</li><li><strong>Styling Limitations: </strong>Shadow DOM encapsulation can lead to challenges in applying global styles, requiring workarounds such as CSS variables or manually overriding styles.</li><li><strong>Tooling and Developer Experience: </strong>Many frontend developers are accustomed to framework-specific tooling and development patterns. Web Components require different approaches to debugging, testing, and dependency management.</li><li><strong>Adoption and Ecosystem Growth: </strong>Although major companies (e.g., Google, Microsoft, Adobe, etc.) use Web Components, many developers still prefer framework-native solutions due to ecosystem maturity and better community support.</li></ul><p>Despite these challenges, Web Components continue to gain traction, especially in areas like <strong>design systems, micro frontends, and enterprise-level applications</strong> where cross-framework compatibility is essential.</p><h3>How to Create a Web Component in Angular</h3><p>Angular, being that amazing full-fledge Javascript framework that we all love, provides tools which allow wrapping standard Angular components as Web Components.</p><p>This section will focus on how to create Web Components in Angular and unlock cross-framework reusability for your UI elements.</p><h4>Step 1: Install Angular Elements</h4><p>Create a new Angular application, or update an existing one, and add @anglar/elements to the project:</p><pre>&gt; ng new angular-web-components --minimal=true --prefix=awc --skip-tests=true --routing=false --experimental-zoneless=true<br>&gt; npm install @angular/elements</pre><p>This example uses a minimal Angular 19.1 project with the “awc” prefix, excluding tests, routing and ZoneJS for simplicity.</p><p>Utilizing Angular 19 with Signals allows us to adopt a Zoneless architecture. This approach enhances performance and simplifies Web Component integration by eliminating the need for polyfill support.</p><h4>Step 2: Update Angular AppComponent</h4><p>For this demonstration, we’ll modify the default AppComponent with the following code:</p><pre>import { Component, input, linkedSignal } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;awc-root&#39;,<br>  imports: [],<br>  template: `<br>  &lt;div&gt;<br>    &lt;h1&gt;{{ title() }}&lt;/h1&gt;<br>    &lt;h2 [class.negative]=&quot;count() &lt; 0&quot;&gt;{{ count() }}&lt;/h2&gt;<br><br>    &lt;button (click)=&quot;count.set(count() + 1)&quot;&gt;Count Up&lt;/button&gt;<br>    &lt;button (click)=&quot;count.set(count() - 1)&quot;&gt;Count Down&lt;/button&gt;<br>    &lt;button (click)=&quot;onReset()&quot;&gt;Reset&lt;/button&gt;<br>  &lt;/div&gt;<br>  `,<br>  styles: `<br>    :host {<br>      --red-color: #af0000;<br>      --green-color: #05860c;<br><br>      text-align: center;<br><br>      h1, h2 {<br>        font-family: Arial, sans-serif;<br>      }<br><br>      h2 {<br>        color: var(--green-color);<br>        font-size: 300%;<br><br>        &amp;.negative {<br>          color: var(--red-color);<br>        }<br>      }<br><br>      button {<br>        background-color: #555555;<br>        border: none;<br>        border-radius: 5px;<br>        color: white;<br>        cursor: pointer;<br>        font-size: 100%;<br>        margin: 5px;<br>        padding: 5px 10px;<br><br>        &amp;:first-of-type {<br>          background-color: var(--green-color);<br>        }<br><br>        &amp;:nth-of-type(2) {<br>          background-color: var(--red-color);<br>        }<br>      }<br>    }    <br>  `<br>})<br>export class AppComponent {<br>  title = input(&#39;Web Components with Angular&#39;);<br>  value = input(0);<br><br>  count = linkedSignal(() =&gt; Number(this.value()));<br><br>  onReset(): void {<br>    this.count.set(Number(this.value()));<br>  }<br>}</pre><p>This component features a basic counter with buttons for increasing, decreasing, and resetting the count. The title and value properties were added to increase the component&#39;s flexibility. Basic styles were applied to make the component less boring.</p><p>To check that everything is working correctly, run ng serve. The browser should display the following screen:</p><figure><img alt="Browser screen with the counter component" src="https://cdn-images-1.medium.com/max/800/1*3yxrIcaRRy6Qs2GjwN08BA.png" /></figure><h4>Step 3: Setup Project for Web Components</h4><p>To make our Angular component usable as a framework-agnostic Web Component, the main.ts file requires the following modifications:</p><pre>import { createApplication } from &#39;@angular/platform-browser&#39;;<br>import { appConfig } from &#39;./app/app.config&#39;;<br>import { AppComponent } from &#39;./app/app.component&#39;;<br>import { createCustomElement } from &#39;@angular/elements&#39;;<br><br>// Replace bootstrapApplication() with the following function:<br>createApplication(appConfig)<br>  .then((app) =&gt; {<br>    const appComponent = createCustomElement(AppComponent, {<br>      injector: app.injector<br>    });<br>    customElements.define(&#39;awc-counter&#39;, appComponent);<br>  })<br>  .catch((err) =&gt; console.error(err));</pre><p>Let’s take a closer look at the newly added code:</p><ul><li>createApplication: Creates an Angular application instance without immediately mounting it to the DOM. This instance shares the configuration from appConfig.</li><li>createCustomElement: Converts AppComponent into a Web Component, using the Angular injector from the created app instance. This gives the custom element access to Angular&#39;s dependency injection system.</li><li>customElements.define: Registers the custom element with the HTML tag name awc-counter that can be used in non-Angular environments (e.g., plain HTML, React, Vue, etc.).</li></ul><h4>Step 4: Update index.html with new Web Component</h4><p>Since we no longer are building the default Angular AppComponent, we need to update the index.html file and replace the awc-root with the new Web Component awc-counter tag.</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot; /&gt;<br>    &lt;title&gt;AngularWebComponents&lt;/title&gt;<br>    &lt;base href=&quot;/&quot; /&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot; /&gt;<br>    &lt;link rel=&quot;icon&quot; type=&quot;image/x-icon&quot; href=&quot;favicon.ico&quot; /&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;!-- Replace awc-root with the new Web Component tag name --&gt;<br>    &lt;awc-counter&gt;&lt;/awc-counter&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Restart the development server by running ng serve and verify that the component is rendered successfully.</p><h4>Step 4: Build the Web Component</h4><p>To build the new Web Component is straightforward, we just need to run ng build and use the main-XXXXXXXX.js file in the dist folder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*evOcCIc4bFJEPW2f1PL0bQ.png" /></figure><p>The resulting file is ready to be used in any project, but we can improve it slightly by removing the hash from the name. Using Web Component JavaScript files <strong>without a hash</strong> in the filename (e.g., main.js instead of main-XXXXXX.js) has several benefits, especially when deploying and integrating them into different environments.</p><p>To improve our output bundle, we can add these following changes to the angular.json file:</p><pre>{<br>  &quot;projects&quot;: {<br>    &quot;angular-web-components&quot;: {<br>      &quot;architect&quot;: {<br>        &quot;build&quot;: {<br>          &quot;options&quot;: {<br>            &quot;styles&quot;: [],              // remove main styles<br>            &quot;extractLicenses&quot;: false,  // remove licenses<br>            &quot;sourceMap&quot;: false,        // remove sourceMaps<br>            &quot;namedChunks&quot;: false       // remove chunks<br>          },<br>          &quot;configurations&quot;: {<br>            &quot;production&quot;: {<br>              &quot;outputHashing&quot;: &quot;none&quot;  // remove name hashing<br>            }<br>          },<br>          &quot;defaultConfiguration&quot;: &quot;production&quot;<br>        }<br>      }<br>    }<br>  }<br>}</pre><p>Re-building the project (ng build) with the previous updates, will result in the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*ay9iR7pZAblTtuI0jPgA6Q.png" /></figure><p>We now have a more clean build and a friendly JavaScript file name that can be used as a Web Component.</p><h4>Step 5: Use the Web Component in Any HTML Page</h4><p>To test our new Web Component, create a an HTML file, add a script tag to include the JavaScript file of the Web Component, and then use the custom element tag in your HTML:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;<br><br>    &lt;title&gt;Web Component Demo&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;awc-counter title=&quot;Hello Web Component&quot; value=&quot;5&quot;&gt;&lt;/awc-counter&gt;<br>  &lt;/body&gt;<br><br>  &lt;script src=&quot;../angular-web-components/browser/main.js&quot;&gt;&lt;/script&gt;<br>&lt;/html&gt;</pre><p>Now, open the index.html file in your browser and see the newly created Web Component working! 🚀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*R1Ak1KQ4WO3EcBqUKC88ug.gif" /></figure><h3>Conclusion</h3><p>Web Components empower developers to build scalable, performant, and maintainable web applications by fostering <strong>modularity</strong>, <strong>reusability</strong>, and <strong>interoperability</strong>.</p><p>As a bridge between frameworks, they facilitate reusability and seamless integration <strong>across different technologies</strong>. While not a universal replacement for framework-specific components, Web Components excel in design systems, micro frontends, and multi-framework projects.</p><p>By utilizing Angular’s @angular/elements, you can create future-proof UI components that are readily accessible across diverse tech stacks.</p><p><strong>References:</strong></p><ul><li><a href="https://github.com/monsieur-ricky/angular-web-components">Article GitHub Repo</a></li><li><a href="https://www.webcomponents.org/">Web Components</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_components">MDN Web Docs</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c72998782cd6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can Signals (and Promises) Replace RxJS in Angular?]]></title>
            <link>https://medium.com/@monsieur_ricky/can-signals-and-promises-replace-rxjs-in-angular-6d142d4878b4?source=rss-6d06bc8a89e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d142d4878b4</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-19]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[promises]]></category>
            <dc:creator><![CDATA[Ricky Lopes]]></dc:creator>
            <pubDate>Mon, 16 Dec 2024 08:31:27 GMT</pubDate>
            <atom:updated>2024-12-16T08:31:27.374Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FwxvkzWmgkAzIHSB1gCDAw.png" /></figure><p>Developing robust and user-friendly applications often involves managing asynchronous tasks and implementing reactive programming patterns. Historically, Angular developers have primarily used RxJS to handle these complexities. However, since the introduction of Signals, the Angular team <a href="https://x.com/mgechev/status/1757164399771717786?ref_src=twsrc%5Etfw%7Ctwcamp%5Etweetembed%7Ctwterm%5E1757164399771717786%7Ctwgr%5E5340ff40d078fd49fbb66d6658b798f72dfe7a8c%7Ctwcon%5Es1_c10&amp;ref_url=https%3A%2F%2Fcdn.embedly.com%2Fwidgets%2Fmedia.html%3Ftype%3Dtext2Fhtmlkey%3Da19fcc184b9711e1b4764040d3dc5c07schema%3Dtwitterurl%3Dhttps3A%2F%2Ftwitter.com%2Fmgechev%2Fstatus%2F1757164399771717786image%3D">is working on making RxJS optional for future versions</a>. This evolution aims to streamline the development process and provide developers with more flexibility in their reactive programming choices.</p><p>Given that this decision is part of Angular’s roadmap, many developers are asking the same question: <strong>Can Signals (and Promises) replace RxJS?</strong></p><p>This article explores the unique roles of these tools, their limitations, and why RxJS remains indispensable for certain use cases.</p><h3>Understanding the Tools</h3><h4>Promises</h4><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promises</a> are part of the ES6 standard and provide a way to handle asynchronous operations. They represent a single value that may be available now, later, or never. Once resolved or rejected, a Promise cannot emit further values.</p><p><strong>Key Features:</strong></p><ul><li>Resolve or reject a single asynchronous value.</li><li>Built-in support for chaining operations via then and error handling via catch.</li><li>Eager execution: Promises start running as soon as they are created.</li></ul><p><strong>Example:</strong></p><pre>const promise = new Promise((resolve) =&gt; {<br>  setTimeout(() =&gt; resolve(&#39;Data received&#39;), 1000);<br>});<br><br>promise.then(console.log); // Logs: &#39;Data received&#39;</pre><h4>Signals</h4><p><a href="https://angular.dev/guide/signals">Signals</a>, introduced in Angular’s reactive model, are designed for state management and provide fine-grained reactivity. They allow developers to track state changes efficiently (i.e., without Zone.js) and without requiring complex patterns or heavy infrastructure.</p><p><strong>Key Features:</strong></p><ul><li>Ideal for managing local, reactive state in Angular.</li><li>Automatically integrate with Angular’s change detection.</li><li>Focus on unidirectional data flow rather than handling asynchronous workflows.</li></ul><p><strong>Example:</strong></p><pre>import { signal } from &#39;@angular/core&#39;;<br><br>const counter = signal(0);<br><br>// Update state<br>counter.update(value =&gt; value + 1);<br><br>// React to state changes<br>console.log(counter()); // Logs: updated value</pre><h4>RxJS Observables</h4><p><a href="https://rxjs.dev/">RxJS</a> Observables are the backbone of reactive programming in Angular. They are not natively part of JavaScript but are deeply integrated into Angular’s ecosystem. Observables allow developers to work with streams of data that can emit multiple values over time.</p><p><strong>Key Features:</strong></p><ul><li>Handle streams of data, not just single values.</li><li>Extensive library of operators for transforming, filtering, and combining data.</li><li>Support for cancellation through subscription management.</li><li>Lazy execution: Observables do not execute until subscribe is called.</li></ul><p><strong>Example:</strong></p><pre>import { Observable } from &#39;rxjs&#39;;<br><br>const observable = new Observable((subscriber) =&gt; {<br>  subscriber.next(&#39;Value 1&#39;);<br>  subscriber.next(&#39;Value 2&#39;);<br>  subscriber.complete();<br>});<br><br>observable.subscribe(console.log); // Logs: &#39;Value 1&#39;, &#39;Value 2&#39;</pre><h3>Comparing Promises, Signals and RxJS</h3><p>Each of these tools serves a unique purpose in development, but their capabilities differ significantly. Comparing them across various aspects like data handling, transformation, and error management can clarify where each shines and where their limitations lie.</p><h4>1. Handling Streams of Data</h4><ul><li><strong>Promises</strong>: Suitable for single asynchronous values, like HTTP requests.</li><li><strong>Signals</strong>: Great for reactive state changes but not designed for asynchronous streams.</li><li><strong>RxJS</strong>: Perfect for event streams, WebSockets, or multiple asynchronous values over time.</li></ul><h4>2. Data Transformation</h4><ul><li><strong>Promises</strong>: Limited transformation capabilities (then, catch).</li><li><strong>Signals</strong>: Lack robust operators for data transformation.</li><li><strong>RxJS</strong>: Extensive operator library (map, filter, mergeMap, etc.) to handle complex pipelines.</li></ul><h4>3. Concurrency Management</h4><ul><li><strong>Promises</strong>: Limited to Promise.all or Promise.race for concurrency.</li><li><strong>Signals</strong>: No built-in support for managing asynchronous workflows (a new async resource api is in the making, but still experimental).</li><li><strong>RxJS</strong>: Operators like switchMap and concatMap provide fine-grained control over concurrent operations.</li></ul><h4>4. Cancellation</h4><ul><li><strong>Promises</strong>: No native support for cancellation; requires workarounds like AbortController.</li><li><strong>Signals</strong>: Automatically clean up unused subscriptions during Angular’s lifecycle but lack explicit cancellation.</li><li><strong>RxJS</strong>: Built-in support for cancellation via unsubscribe.</li></ul><h4>5. Error Handling</h4><ul><li><strong>Promises</strong>: Basic error handling through .catch().</li><li><strong>Signals</strong>: Do not natively handle errors in asynchronous workflows (the upcoming resource api will allow error handling).</li><li><strong>RxJS</strong>: Robust error-handling patterns (catchError, retry) for recovering mid-stream.</li></ul><h3>RxJS Key Strengths</h3><p>While Promises and Signals are powerful tools, they lack the depth and breadth of functionality to manage complex asynchronous and reactive programming scenarios. RxJS outperforms Promises and Signals in these key areas:</p><h4>1. Streams and Real-Time Data</h4><p>RxJS excels at handling <strong>streams of data</strong>, such as:</p><ul><li>WebSocket updates.</li><li>User input streams (e.g., search suggestions).</li><li>Continuous state synchronisation across components.</li></ul><h4>2. Advanced Reactive Workflows</h4><p>RxJS’s operator library makes it possible to compose complex workflows that Promises and Signals cannot handle easily. For example:</p><ul><li>Combining multiple data sources (combineLatest).</li><li>Switching between streams (switchMap).</li><li>Managing throttling and debouncing (debounceTime).</li></ul><h3>When to Use Each Tool</h3><p>Choosing the right tool for the job is crucial in development. Each of these tools has specific strengths and is best suited for particular scenarios. Understanding their ideal use cases can help you write cleaner, more efficient code.</p><h4>Use Promises When:</h4><ul><li>Handling simple, one-time asynchronous operations.</li><li>Using async/await syntax for readability.</li></ul><h4>Use Signals When:</h4><ul><li>Managing local, reactive state in Angular’s component-based architecture.</li><li>Simplifying UI updates with Angular’s new reactive primitives.</li></ul><h4>Use RxJS When:</h4><ul><li>Working with streams of data.</li><li>Building complex reactive workflows.</li><li>Using Angular’s core features that depend on Observables.</li></ul><h3>Conclusion</h3><p>Promises, Signals, and RxJS each have their place in Angular development. While Promises and Signals are powerful tools, they lack the comprehensive capabilities of RxJS for managing streams, transforming data, and handling complex workflows.</p><p>For developers building modern, reactive Angular applications, <strong>RxJS remains an irreplaceable part of the toolkit</strong>. <strong>In many cases, these tools complement each other rather than compete.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d142d4878b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modern Credit Card UI app with Zoneless Angular and the CSS @property]]></title>
            <link>https://medium.com/@monsieur_ricky/modern-credit-card-ui-app-with-zoneless-angular-and-the-css-property-6b2d76cef2c1?source=rss-6d06bc8a89e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b2d76cef2c1</guid>
            <category><![CDATA[angular-19]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[scss]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Ricky Lopes]]></dc:creator>
            <pubDate>Mon, 02 Dec 2024 18:06:02 GMT</pubDate>
            <atom:updated>2024-12-02T18:06:02.022Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AiIPqzA2cN-itOrIrOs0Rw.png" /></figure><p>As frontend developers, we’re always looking for innovative ways to deliver seamless and visually appealing user experiences. In my latest demo project, I decided to tackle a familiar challenge: building an interactive <strong>Credit Card UI </strong>app. But this time, I added a twist — <strong>no Zone.js</strong> in Angular and leveraging CSS <strong>@property</strong> for background transitions.</p><h3>The Idea</h3><p>The goal was simple: create an application where users can input credit card details and see the updates reflected in a visually striking UI. To make things more exciting, I wanted to use Angular 19 without Zone.js and allow users to switch between card styles with smooth transitions, showcasing the flexibility of CSS <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/@property">@property</a>.</p><h3>Why Zone.js-Free Angular?</h3><p>Angular traditionally relies on Zone.js for change detection, which simplifies the framework but can sometimes lead to performance overhead. Since the Angular team is <a href="https://angular.dev/guide/experimental/zoneless">working on removing this dependency</a>, I wanted to explore the framework’s potential without Zone.js, using Signals to keep things lean and efficient.</p><h4>How to enable a zoneless Angular app</h4><p><strong>1. Enable the experimental zoneless change detection:</strong></p><pre>// Standalone bootstrap<br>bootstrapApplication(MyApp, {providers: [<br>  provideExperimentalZonelessChangeDetection(),<br>]});<br><br>// NgModule bootstrap<br>platformBrowser().bootstrapModule(AppModule);<br>@NgModule({<br>  providers: [provideExperimentalZonelessChangeDetection()]<br>})<br>export class AppModule {}</pre><p><strong>2. Update </strong><strong>angular.json removing the polyfills:</strong></p><pre>// before:<br>&quot;polyfills&quot;: [<br>   &quot;zone.js&quot;<br>],<br><br>// after<br>&quot;polyfills&quot;: [],</pre><p>Note: Projects that use a polyfills.ts file should remove import &#39;zone.js&#39;; and import &#39;zone.js/testing&#39;; from that file.</p><p><strong>3. Uninstall zone.js dependency:</strong></p><pre>npm uninstall zone.js</pre><p>Removing Zone.js not only streamlines performance but also reduces the bundle size.</p><h3>The Power of CSS @property</h3><p>I wanted to add cool color gradient styles to the cards, and also do some neat transition effects when changing the styles.</p><p>Since CSS transitions cannot directly animate linear-gradient, because gradients are considered part of the image data type and not simple color values. Transitions work by interpolating numeric values or color components, which is not feasible for gradients since they are complex constructs akin to images. There are some <a href="https://keithjgrant.com/posts/2017/07/transitioning-gradients/">hacks</a> to overcome this issue, but I wanted to do something cleaner and more future proof. So, that’s where @property comes into play…</p><p>The CSS @property rule differs from standard <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties">CSS Custom Properties</a> by offering greater control, such as defining whether it inherits values from a parent, setting an initial value, and specifying type constraints. This is especially useful for transitions, animations, and type enforcement.</p><h4>How to animate gradient backgrounds with @property</h4><p>Here’s a simple example on how to apply transition effects to gradient backgrounds:</p><pre>// Only accepts valid angle values<br>@property --angle {<br>  syntax: &quot;&lt;angle&gt;&quot;;<br>  inherits: false;<br>  initial-value: 135deg;<br>}<br><br>// Only accepts valid color values (multiple comma separated)<br>@property --card-color {<br>  syntax: &quot;&lt;color&gt;#&quot;;<br>  inherits: false;<br>  initial-value: #111111, #888888;<br>}<br><br>.card {<br>  // Apply the default gradient styles<br>  background: linear-gradient(var(--angle), var(--card-color));<br><br>  // Transition effect based on the defined properties<br>  transition: --angle 1s, --card-color 0.8s;<br><br>  &amp;--light {<br>    --angle: 300deg;<br>    --card-color: #FAF9F6, #F9F6EE;<br>  }<br>}</pre><p>In the previous example, applying the .card--light class to the card element updates the --angle and --card-color properties, triggering a smooth transition background effect. It’s that easy!</p><h3>Final Result</h3><p>Here’s a short video of the final application:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FDlGMc5Xir5I&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DDlGMc5Xir5I&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FDlGMc5Xir5I%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b86e496cc3d42c1dd81ac8fa48eedecb/href">https://medium.com/media/b86e496cc3d42c1dd81ac8fa48eedecb/href</a></iframe><h4>Try It Out!</h4><p>The project is open-source, and I’d love for you to check it out, play around with the code, and share your feedback.</p><p>👉 <a href="https://monsieur-ricky.github.io/ng-credit-card-ui/">Live Demo</a><br>👉 <a href="https://github.com/monsieur-ricky/ng-credit-card-ui">GitHub Repository</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b2d76cef2c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying Local Storage Management in Angular]]></title>
            <link>https://medium.com/@monsieur_ricky/simplifying-local-storage-management-in-angular-733a791d6d84?source=rss-6d06bc8a89e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/733a791d6d84</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-17]]></category>
            <category><![CDATA[angular2]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Ricky Lopes]]></dc:creator>
            <pubDate>Sun, 02 Jun 2024 09:31:31 GMT</pubDate>
            <atom:updated>2024-06-02T09:31:31.612Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rTyD_YlV0mg5bRuWzA6KgA.jpeg" /></figure><p>Local storage is a <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage">web storage API</a> that allows you to store data locally within the browser. This data persists even after the browser window or tab is closed, making it ideal for storing user preferences, application state, or other data that needs to be accessed across sessions.</p><p>While <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage">localStorage</a> is easy and straightforward to use, directly interacting with it throughout your Angular application isn’t recommended. You can read more about that in this article:</p><p><a href="https://medium.com/@monsieur_ricky/accessing-browser-global-objects-in-angular-with-dependency-injection-3ebc9d764e84">Accessing Browser Global Objects in Angular with Dependency Injection</a></p><p>By encapsulating <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage">localStorage</a> operations within a <a href="https://angular.dev/guide/di/creating-injectable-service#creating-an-injectable-service">service</a>, not only can we create a reusable and testable solution, but also simplify and enhance our local storage management.</p><h4>Custom Local Storage Service</h4><p>In the following example, we have a custom service named LocalStorageService that provides wrappers for all of the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage">localStorage</a> methods:</p><pre>import { Injectable, inject } from &#39;@angular/core&#39;;<br>import { DOCUMENT } from &#39;@angular/common&#39;;<br><br>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class LocalStorageService {<br>  private readonly localStorage = inject(DOCUMENT)?.defaultView?.localStorage;<br><br>  get&lt;T&gt;(key: string): T | null {<br>    const item = this.localStorage?.getItem(key);<br><br>    if (!item) {<br>      return null;<br>    }<br><br>    return this.isJSONValid(item) ? (JSON.parse(item) as T) : (item as T);<br>  }<br><br>  set(key: string, value: unknown): void {<br>    this.localStorage?.setItem(key, JSON.stringify(value));<br>  }<br><br>  remove(key: string): void {<br>    this.localStorage?.removeItem(key);<br>  }<br>  <br>  removeKeys(keys: string[]): void {<br>    keys.forEach(key =&gt; this.localStorage?.removeItem(key));<br>  }<br><br>  clear(): void {<br>    this.localStorage?.clear();<br>  }<br><br>  private isJSONValid(value: string): boolean {<br>    try {<br>      JSON.parse(value);<br>      return true;<br>    } catch (error) {<br>      return false;<br>    }<br>  }<br>}</pre><p>The provided example has some interesting features that enhances the default <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage">localStorage</a> methods. Let’s go through them:</p><ul><li>The get method retrieves a value from <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage">localStorage</a> based on a given key. The interesting part is that it’s a <a href="https://www.typescriptlang.org/docs/handbook/2/generics.html">generic function</a> and attempts to parse the value as a given <a href="https://www.typescriptlang.org/docs/handbook/2/objects.html">Type</a>, providing type safety and ensuring that structured data is correctly handled.</li><li>The set method stores a value in <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage">localStorage</a>, converting it to a JSON string to preserve its structure.</li><li>The remove and clear methods delete a specific key and all keys, respectively, from the browser’s local storage.</li><li>The removeKeys is an extra feature that allows us to remove an array of given keys from the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage">localStorage</a>.</li><li>The private isJSONValid method is being used when retrieving a value from the local storage and checks if a string can be parsed as JSON, ensuring data integrity.</li></ul><p>Another thing worth mentioning is the use of the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining">Optional Chaining</a> operator in our code. This gracefully handles scenarios where <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage">localStorage</a> might be unavailable preventing potential errors during retrieval.</p><h4>Local Service Usage Example</h4><p>Now that we have created our custom LocalStorageService we can use it throughout our Angular project. Thanks to Angular’s Dependency Injection (DI), our service can be injected into any component, directive, pipe or service:</p><pre>import { inject } from &#39;@angular/core&#39;;<br>import { LocalStorageService } from &#39;./local-storage.service&#39;;<br><br>interface UserSetting {<br>  name: string;<br>  preferences: {<br>    theme: string;<br>    language: string;<br>  };<br>}<br><br>export class TestComponent {<br>  private readonly localStorageService = inject(LocalStorageService);<br><br>  setUserSettings(userSettings: UserSetting): void {<br>    this.localStorageService.set(&#39;UserSettingKey&#39;, userSettings);<br>  }<br><br>  getUserSettings(): UserSetting | null {<br>    return this.localStorageService.get&lt;UserSetting&gt;(&#39;UserSettingKey&#39;);<br>  }<br><br>  removeUserSettings(): void {<br>    return this.localStorageService.remove(&#39;UserSettingKey&#39;);<br>  }<br>}</pre><p>In this example, the LocalStorageService is injected into a TestComponent that provides the following features:</p><ul><li>Storing User Settings: The setUserSettings method accepts a UserSetting object and stores it in <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage">localStorage</a> under the key UserSettingKey. This method ensures that the user settings are persisted in the browser&#39;s local storage as a JSON string, preserving the structure of the data.</li><li>Retrieving User Settings: The getUserSettings method retrieves the value associated with UserSettingKey from <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage">localStorage</a>. It uses a generic return type UserSetting, ensuring type safety and that the returned data is correctly parsed back into a UserSetting object. If no value is found for the key, it returns null.</li><li>Removing User Settings: The removeUserSettings method removes the item associated with UserSettingKey from <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage">localStorage</a>. This clears the saved user settings from the browser&#39;s local storage, effectively resetting the stored state.</li></ul><p>If we need to remove multiple values from the local storage without clearing the whole storage, we can accomplish that easily with our removeKeys() function:</p><pre>import { inject } from &#39;@angular/core&#39;;<br>import { LocalStorageService } from &#39;./local-storage.service&#39;;<br><br>export class AnotherTestComponent {<br>  private readonly localStorageService = inject(LocalStorageService);<br><br>  removeListOfKeys(): void {<br>    return this.localStorageService.removeKeys([<br>      &#39;ExampleKeyA&#39;,<br>      &#39;ExampleKeyB&#39;,<br>      &#39;ExampleKeyC&#39;<br>    ]);<br>  }<br>}</pre><p>In previous example, the removeListOfKeys method calls the removeKeys function of the LocalStorageService, passing an array of keys to be removed. This method effectively removes the specified keys and their associated values from the browser’s local storage, allowing an easy-to-use bulk deletion of items.</p><h4>Conclusion</h4><p>By encapsulating <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage">localStorage</a> interactions within a service, we ensure our code remains clean, maintainable, and testable. This approach also makes it easier to extend functionality, such as adding encryption for stored data or implementing fallbacks for environments where <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage">localStorage</a> is not available.</p><p>Creating a custom Angular service for <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage">localStorage</a> is a simple yet powerful way to manage client-side storage in your applications. By following the practices outlined in this article, you can enhance your application&#39;s local store management, leading to a more robust and maintainable codebase.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=733a791d6d84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Accessing Browser Global Objects in Angular with Dependency Injection]]></title>
            <link>https://medium.com/@monsieur_ricky/accessing-browser-global-objects-in-angular-with-dependency-injection-3ebc9d764e84?source=rss-6d06bc8a89e2------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ebc9d764e84</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[angular-17]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Ricky Lopes]]></dc:creator>
            <pubDate>Fri, 17 May 2024 08:31:33 GMT</pubDate>
            <atom:updated>2024-05-17T08:31:33.745Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mmeqSA8FZsPOaIDNJUtGTg.jpeg" /></figure><p>In Angular applications, we often need to interact with native browser APIs or global objects like <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window">window</a> or <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document">document</a>. While directly referencing these objects is possible, it’s not recommended because it leads to tighter coupling, makes testing more difficult, and ties your code to a specific platform (i.e., browser).</p><p>This is where Dependency Injection (DI) comes to the rescue...</p><h3>Angular’s Document Token</h3><p>In Angular, we have the DOCUMENT token that allows us to inject the browser&#39;s <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document">document</a> object. This token is part of Angular&#39;s platform-browser package and will provide an appropriate object for us, whether our app is running on the server or in the browser.</p><p>The following example shows how we can inject the DOCUMENT token and access one of its functions in a Component:</p><pre>import { DOCUMENT } from &#39;@angular/common&#39;;<br>import { inject } from &#39;@angular/core&#39;;<br><br>export class TestComponent {<br>  private readonly document = inject(DOCUMENT);<br><br>  reloadPage(): void {<br>    this.document?.location?.reload();<br>  }<br>}</pre><p>The previous example is quite simple: we import and inject Angular’s DOCUMENT token, use it to access the browser’s <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/location">location</a> property, and execute the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Location/reload">reload</a> method.</p><h3>Window Property Access</h3><p>If we need to access the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window">window</a> property, we should use the same DOCUMENT token:</p><pre>import { DOCUMENT } from &#39;@angular/common&#39;;<br>import { inject } from &#39;@angular/core&#39;;<br><br>export class TestComponent {<br>  private readonly document = inject(DOCUMENT);<br>  private readonly window = this.document?.defaultView<br><br>  getLanguage(): string {<br>    return this.window?.navigator?.language<br>  }<br>}</pre><p>By utilizing the injected DOCUMENT, we access the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window">window</a> object through its <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/defaultView">defaultView</a> property, granting access to all of its functions and objects. In this specific example, we retrieve the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Navigator">navigator</a> object, which provides a string representing the language of the browser&#39;s user interface.</p><p>This approach already makes working with browser specific APIs much easier and safer. But if we find ourselves needing to use the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window">window</a> object often, we can just create our custom token.</p><h3>Custom Window Token</h3><p>The following example shows how we can create a custom WINDOW token, similar to Angular’s DOCUMENT, and use it throughout our project:</p><pre>// browser-global-tokens.ts<br>import { DOCUMENT } from &#39;@angular/common&#39;;<br>import { InjectionToken, inject } from &#39;@angular/core&#39;;<br><br>/**<br> * Injection token for the global window object.<br> */<br>export const WINDOW = new InjectionToken&lt;Window&gt;(&#39;Global window object&#39;, {<br>  factory: (): Window =&gt; inject(DOCUMENT)?.defaultView<br>});</pre><p>The above code snippet defines an injection token named WINDOW that is created with a factory function. This function retrieves the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/defaultView">defaultView</a> property of the DOCUMENT object using inject(DOCUMENT).defaultView, giving us access to the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window">window</a> object within the Angular application via Dependency Injection (DI).</p><p>Let’s update the TestComponent example with our new WINDOW token:</p><pre>import { WINDOW } from &#39;./browser-global-tokens.ts&#39;;<br>import { inject } from &#39;@angular/core&#39;;<br><br>export class TestComponent {<br>  private readonly window = inject(WINDOW);<br><br>  getLanguage(): string {<br>    return this.window?.navigator?.language<br>  }<br>}</pre><p>We were able to slightly simplify the code by directly using our custom WINDOW token to access the browser’s language.</p><h3>Conclusion</h3><p>We’ve explored how Angular’s Dependency Injection mechanism can be leveraged to inject global objects like <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window">window</a> into our applications in a safe and maintainable manner. By using injection tokens and factory functions, we can seamlessly integrate these global objects into our code while adhering to Angular best practices.</p><p>Avoiding direct access to global objects in Angular applications not only promotes better code organization and testability, but also enhances type safety and cross-platform compatibility.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ebc9d764e84" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>