<?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[Multitude IT Labs - Medium]]></title>
        <description><![CDATA[Multitude IT Labs is an IT hub of 100+ IT specialists based in Bratislava, Slovakia. Supporting the needs of the Multitude group - Medium]]></description>
        <link>https://medium.com/multitude-it-labs?source=rss----5c76af6b2fa7---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Multitude IT Labs - Medium</title>
            <link>https://medium.com/multitude-it-labs?source=rss----5c76af6b2fa7---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 18:11:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/multitude-it-labs" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Exploiting Unvalidated Redirects for XSS]]></title>
            <link>https://medium.com/multitude-it-labs/exploiting-unvalidated-redirects-for-xss-9ae6c213c4e1?source=rss----5c76af6b2fa7---4</link>
            <guid isPermaLink="false">https://medium.com/p/9ae6c213c4e1</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Eduard Krivanek]]></dc:creator>
            <pubDate>Wed, 07 Jan 2026 09:14:29 GMT</pubDate>
            <atom:updated>2026-01-07T09:14:28.690Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Rm5KSQ3hpdq3xVluaL-gw.jpeg" /><figcaption>Article Cover Image</figcaption></figure><p>Being in web development for a while, you start exploring different domains than just mastering your favourite framework. I decided to learn more about web security. We hear a lot about preventing our web apps from exploitation, sanitize data, never trust user inputs, so on, so on… the truth is that we overlook (willingly or accidentally) security holes when developing new features, which can lead exploits and production outage.</p><p>In this post, I want to explore how an attacker can potentially steal client side information or inject scripts using unvalidated redirects. For this example we will use a dashboard application in Angular, an authentication app in React, and a server in NestJS. In real life you would have a dedicated identity server, just for authentication, but this setup is good enough for our demonstration.</p><h3>The Scenario</h3><p>Here is the scenario. Imagine you are in a large organization with multiple production applications. Each app lives on a separate URL, fulfilling a different business purpose. However, you want a centralized login system. You have one authentication endpoint where each user logs in, and the server verifies their identity. Something as showed on the following image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TMT3H_aYhI6tL8km0jDozA.png" /><figcaption>Gemini: Multi App Authentication Example</figcaption></figure><h3>Expected Behaviour</h3><p>First I want to describe the expected behaviour (”happy path”) with this approach, how we assume the user should use the app.</p><ul><li>Initial load — You start on the main application (http://localhost:4200), we use localhost, but the can be any kind of domain name.</li><li>Redirect to auth — Since you are not logged in (no token in LocalStorage), the app redirects you to the Auth Server (http://localhost:4201).</li><li>State passing — We send a base64 encoded state query parameter (context) to the auth app from the origin. Encoding data as who created the redirection, the origin name (appName), where to return (redirectUrl), and a tracking ID (traceId) for monitoring.</li><li>Success — Once authenticated, the user is redirected back to the original app (http://localhost:4200 - information from the redirectUrl), with a JWT token in the query parameter.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5nPIFW_IJMfZ3wNFVDUhsA.gif" /><figcaption>Authentication Expected Behaviour</figcaption></figure><p>The decoded state query param passes to the auth application can be seen in the “debug” green section. When user logs in, back in the original (Angular) app, we grab the JWT token, remove it from the query param and save it into localstorage and to the application internal state. In the GIF above you can see displayed in console this JWT token. This is how it’s done in Angular, just for some overview:</p><pre>@Component({ /* ... */ })<br>export class App {<br>  private readonly appState = inject(AppState);<br>  private readonly router = inject(Router);<br><br>  constructor() {<br>    afterNextRender(() =&gt; {<br>      // check URL for token on initial load - user authenticated<br>      const params = new URLSearchParams(window.location.search);<br>      const token = params.get(&#39;token&#39;) as string | null;<br><br>      if (!token) {<br>        return;<br>      }<br>			<br>      // custom logic to parse the JWT into normal object<br>      const decodedToken = customDecodeToken&lt;User&gt;(token);<br><br>      if (decodedToken) {<br>        // clean URL to remove token param<br>        window.history.replaceState({}, document.title, &#39;/&#39;);<br>				<br>	// save the user to the application state<br>        this.appState.setData(&#39;token&#39;, token);<br>        this.appState.setData(&#39;user&#39;, decodedToken);<br>				<br>	// persist data for application reload<br>        localStorage.setItem(&#39;access_token&#39;, token);<br>        <br>        // redirect to the app<br>        this.router.navigate([&#39;/overview&#39;]);<br>      }<br>    });<br>  }<br>}</pre><h3>Overview Of XSS Vulnerability In Redirection</h3><p>The application works fine, so where exactly is the potential bug ? We need to take a look at the React (authentication) app. Even if you are not familiar with React, the logic here is straightforward:</p><pre>import { useEffect, useState } from &#39;react&#39;;<br><br>function App() {<br>  // used in HTML to set auth data<br>  const [username, setUsername] = useState(authLogin.username);<br>  const [password, setPassword] = useState(authLogin.password);<br><br>  // decoded from the URL `state` query param<br>  const [appName, setAppName] = useState(&#39;&#39;);<br>  const [redirectUrl, setRedirectUrl] = useState(&#39;&#39;);<br>  const [traceId, setTraceId] = useState(&#39;&#39;);<br><br>  useEffect(() =&gt; {<br>    // read the &#39;state&#39; query param<br>    const params = new URLSearchParams(window.location.search);<br>    const stateParam = params.get(&#39;state&#39;);<br><br>    if (!stateParam) {<br>	return; <br>     }<br><br>    // decode base64 - vulnerability<br>    const decodedString = atob(stateParam);<br>    const stateData = JSON.parse(decodedString);<br><br>    // extract context information<br>    if (stateData.appName) {<br>       setAppName(stateData.appName);<br>    }<br>    if (stateData.redirectUrl) {<br>       setRedirectUrl(stateData.redirectUrl);<br>    }<br>    if (stateData.traceId) {<br>       setTraceId(stateData.traceId);    <br>    }<br>  }, []);<br><br>  const handleLogin = async (e: any) =&gt; {<br>    e.preventDefault();<br><br>    try {<br>      // send auth to NestJS backend<br>      const response = await fetch(&#39;&lt;http://localhost:3000/api/auth/login&gt;&#39;, {<br>        method: &#39;POST&#39;,<br>        headers: {<br>          &#39;Content-Type&#39;: &#39;application/json&#39;,<br>        },<br>        body: JSON.stringify({ username, password }),<br>      });<br>			<br>      // invalid credentials <br>      if (!response.ok) {<br>        throw new Error(&#39;Invalid credentials&#39;);<br>      }<br><br>      const data = await response.json();<br>      const token = data.access_token;<br><br>      // handle redirect<br>      if (redirectUrl) {<br>        const hasToken = redirectUrl.includes(&#39;{token}&#39;);<br>        // check if contains the {token} query param, if so replace it or append at the end<br>        const finalUrl = hasToken ? redirectUrl.replace(&#39;{token}&#39;, token) : `${redirectUrl}?token=${token}`;<br>        // redirect back to original domain<br>        window.location.href = finalUrl;<br>      }<br>    } catch (error) {<br>      alert(&#39;Login Failed: Invalid username or password&#39;);<br>      console.error(error);<br>    }<br>  };<br><br>  return ( /* HTML .... */ );<br>}<br><br>export default App;</pre><p>I wouldn’t personally have known that there was a bug if I hadn’t built this example specifically to test it. The vulnerability is hidden in how we handle the redirect using window.location.href.</p><p>This property is used to navigate the user to a different domain. If we set it to window.location.href = &quot;&lt;https://google.com&gt;&quot;, we go to Google. Where is the problem tho? If we do not validate the redirectUrl, it is possible to execute code like this:</p><pre>window.location.href = &quot;javascript:alert(&#39;XSS Executed&#39;);window.location.href=&#39;&lt;https://www.google.com&gt;&#39;;//&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cz_YXasN_f13Um-B8ynrFA.gif" /><figcaption>Redirect XSS Example</figcaption></figure><p>Now, of course, this demonstration will not work on every domain. If you are outside localhost, you may receive an Error as displayed below. The script execution is prevented by CSP (Content Security Policy). This header tells the browser to only execute code from trusted JS file. For this demonstration, we assume the application has a missing or weak CSP (allowing ‘unsafe-inline’), which can happen in legacy apps. Most of the time you have a strict CSP, therefore executing such a script is not that simple. Currently we ignore this defense mechanism, we just want to demonstrate one of the potential vulnerabilities, as the attacker could find a different backdoor to execute the following attack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DAQ1jZS-sk1P1BAu5Ekh6Q.png" /><figcaption>CSP Error Example</figcaption></figure><h3>Real World Demonstration</h3><p>Since we are not sanitizing the redirectUrl, that is parsed on the auth React app, we can encode Javascript code inside it. When we visit the auth application, all the information is encoded to the state query param by base64. Therefore we can construct a malicious payload and encode it:</p><pre>{<br>  &quot;appName&quot;: &quot;Workday Clone (Angular)&quot;,<br>  &quot;traceId&quot;: &quot;Example-123&quot;,<br>  &quot;redirectUrl&quot;: &quot;javascript:alert(&#39;XSS Executed&#39;);window.location.href=&#39;&lt;http://localhost:4200?token={token}&gt;&#39;&quot;<br>}<br><br>// will result to the following hash:<br>/**<br>ewogICAgICJhcHBOYW1lIjogIldvcmtkYXkgQ2xvbmUgKEFuZ3VsYXIpIiwKICAidHJhY2VJZCI6<br>ICJFeGFtcGxlLTEyMyIsCiAgInJlZGlyZWN0VXJsIjogImphdmFzY3JpcHQ6YWxlcnQoJ1hTUyBF<br>eGVjdXRlZCcpO3dpbmRvdy5sb2NhdGlvbi5ocmVmPSdodHRwOi8vbG9jYWxob3N0OjQyMDA/dG9r<br>ZW49e3Rva2VufSciCn0=<br>**/</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qZIJU6Lc4iwTz_CI-4NCNQ.gif" /><figcaption>XSS Alert Example</figcaption></figure><p>Both application is running on localhost, but the domains can be anything. The idea of this attack is simple:</p><ul><li>The attacker sends a victim a link to the legitimate login page, but with a modified state parameter.</li><li>The victim logs in securely.</li><li>The React app reads the malicious redirectUrl.</li><li>The browser executes the injected script (XSS).</li><li>The script then redirects the user to the actual app, so the victim has no idea what happened.</li></ul><p>On this example you see a harmless alert for a demonstration. But what if we wanted to be destructive? We could inject code in the state query param to steal the user&#39;s localStorage, cookies and the JTW token, and send them to an external server using fetch() before redirecting them.</p><pre>const t = &#39;{token}&#39;;<br><br>const capturedData = {<br>   cookies: document.cookie,<br>   storage: localStorage,<br>   token: t<br>};<br><br>// attacker would use fetch() to log somewhere this data<br>alert(JSON.stringify(capturedData, null ,2));<br><br>window.location.href = &#39;&lt;http://localhost:4200?token=&gt;&#39; + t;<br><br>// --------------------<br>/** -- Generated Base64<br>ewogICAgICJhcHBOYW1lIjogIldvcmtkYXkgQ2xvbmUgKEFuZ3VsYXIpIiwKICAgICAgInRyYWNl<br>SWQiOiAic3AtMTIzIiwKICAgICAgInJlZGlyZWN0VXJsIjogImphdmFzY3JpcHQ6Y29uc3QgdD0n<br>e3Rva2VufSc7Y29uc3QgY2FwdHVyZWREYXRhPXtjb29raWVzOmRvY3VtZW50LmNvb2tpZSxzdG9y<br>YWdlOiBsb2NhbFN0b3JhZ2UsdG9rZW46dH07YWxlcnQoSlNPTi5zdHJpbmdpZnkoY2FwdHVyZWRE<br>YXRhLG51bGwsMikpO3dpbmRvdy5sb2NhdGlvbi5ocmVmPSdodHRwOi8vbG9jYWxob3N0OjQyMDA/<br>dG9rZW49Jyt0OyIKfQ==<br>**/</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tKdWp1zjgSYAaAfCMPxdCw.gif" /><figcaption>XSS stealing client data</figcaption></figure><p>In the example above, we successfully displayed (or “stole”) client’s information. The user was still able to log in, meaning the attack was executed silently. The attacker now has the user’s valid token and can impersonate them.</p><p>A confusing part may be how the attacker got the JWT token. This goes back to the this code redirectUrl.replace(&#39;{token}&#39;, token). The redirectUrl is the whole JS displayed above as a string:</p><pre>&quot;redirectUrl&quot;: &quot;javascript:const t=&#39;{token}&#39;;const capturedData={cookies:document.cookie,storage: localStorage,token:t};alert(JSON.stringify(capturedData,null,2));window.location.href=&#39;&lt;http://localhost:4200?token=&#39;+t;&quot;&gt;</pre><p>The attacker knows the replace part exists in the React app. Yes, the JS is minified in PROD, but let’s skip the logic how the attacker knows about this vulnerability. The auth application sees the {token} placeholder and injects the real JWT right into it and then just executes the whole JS inside the redirectUrl.</p><p>Keep in mind that sometimes when the query param (state) is too long, it can fail on parsing/decoding. Therefore the attacker could use JS minification and URL shortener tools to avoid parsing crashes and suspicion from the victim side.</p><p>Even if our application had a strict CSP that would have blocked the javascript: execution, we would still have a major security hole, an “Open Redirect Vulnerability”. The attacker could set the redirectUrl to http://fake-login-page.com. The user logs inside the real app, the server returns a valid token, and then auth app immediately redirects the use to the attacker&#39;s phishing site (which looks the same as our auth app). The victim might re-enter their credentials into the fake site. Therefore we should have an allowlist, list of valid domain where the user can be redirected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x3vSbM4gPQJ-5x8PEQpdSQ.png" /><figcaption>Open Redirect Phishing Attack</figcaption></figure><h3>Avoid XSS Vulnerability In Redirection</h3><p>This demo tried to mimic some real-world scenario, but also it was designed such that we will be able to execute this XSS redirect attack. Production applications are probably much more protected than my demo, but if your app looks like something that I’ve presented, here are some ways how you can prevent this attack:</p><ul><li><strong>Temporary Token — </strong>Instead of sending the actual JWT access token in the URL, the auth server should generate a one time use “authorization code” and pass that in the redirect. When the Angular dashboard receives this code, it requests the backend to exchange it for the real JWT. This works because the code is valid only for a few seconds, making it useless even if captured.</li><li><strong>Token Reuse Detection </strong>— The backend should mark the real token as “used” in the database immediately after it is exchanged or validated for the first time. You can even attached the requester IP address to the specific token. If the system detects a second attempt to use the same token (“replay attack”), it should immediately invalidate that token… maybe even alert the security team.</li><li><strong>Domain Validation </strong>— The most immediate fix is to validate the redirectUrl on the client side, sanitize the data. Probably creating one URL validation function that checks if the contains any javascript: code and whether it starts with http: or https:. Even an “allowedList” of trusted domains that sits on the authentication app can help to prevent redirection to any phishing site.</li></ul><p>There are many more ways how to prevent this attack. I am not a security expect, but this is an interesting example I bumped into when I was researching about security, so I wanted to share my findings. Hope you liked this article, catch more of my stuff on <a href="https://dev.to/krivanek06">dev.to</a>, connect with me on <a href="https://www.linkedin.com/in/eduard-krivanek">LinkedIn</a> or check my <a href="https://eduardkrivanek.com/">Personal Website</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ae6c213c4e1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/multitude-it-labs/exploiting-unvalidated-redirects-for-xss-9ae6c213c4e1">Exploiting Unvalidated Redirects for XSS</a> was originally published in <a href="https://medium.com/multitude-it-labs">Multitude IT Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular — Custom MatPaginator Styling]]></title>
            <link>https://medium.com/multitude-it-labs/angular-custom-matpaginator-styling-fa91e697fd88?source=rss----5c76af6b2fa7---4</link>
            <guid isPermaLink="false">https://medium.com/p/fa91e697fd88</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Eduard Krivanek]]></dc:creator>
            <pubDate>Fri, 28 Nov 2025 13:04:29 GMT</pubDate>
            <atom:updated>2025-11-28T13:04:28.422Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular - Custom MatPaginator Styling</h3><p>One of my more popular articles that I’ve published is <a href="https://dev.to/krivanek06/angular-matpaginator-custom-styling-dkb?utm_source=chatgpt.com">Angular: MatPaginator Custom Styling</a>, which shows how to transform Angular Material’s paginator (on a mat-table) using a custom directive to make it look more appealing.</p><p>I decided to update this article because since then, two major things have changed. It was originally written for Angular v14, and since then we’ve received the major <a href="https://v17.material.angular.dev/guide/mdc-migration">Angular Material MDC components</a>, which caused quite a few issues for people updating their projects, along with some smaller Angular improvements. Also, in my previous article, I was accessing some private methods of the MatPaginator component. In the GIF below, you can see the final example we’ll be building. You can also find the full source code in this <a href="https://github.com/krivanek06/stackblitz-angular-custom-mat-paginator">GitHub repository</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qW76RlIvSYV-moQUOOvWIQ.gif" /><figcaption>Angular Custom Paginator End Result</figcaption></figure><p>I will start this blog post by showing the full code section, you can always come back to it, and then we’ll go through some of the more interesting or not that obvious parts. You might already have a table component displaying data, something like this:</p><pre>import { afterNextRender, Component, viewChild } from &#39;@angular/core&#39;;<br>import { MatPaginator, MatPaginatorModule } from &#39;@angular/material/paginator&#39;;<br>import { MatTableDataSource, MatTableModule } from &#39;@angular/material/table&#39;;<br><br>type Data = { position: number; name: string; weight: number; symbol: string };<br><br>@Component({<br>  selector: &#39;app-test-table&#39;,<br>  imports: [MatTableModule, MatPaginatorModule, BubblePaginationDirective],<br>  template: `<br>    &lt;table mat-table [dataSource]=&quot;dataSource&quot;&gt;<br>      &lt;!-- Position Column --&gt;<br>      &lt;ng-container matColumnDef=&quot;position&quot;&gt;<br>        &lt;th mat-header-cell *matHeaderCellDef&gt;No.&lt;/th&gt;<br>        &lt;td mat-cell *matCellDef=&quot;let element&quot;&gt;{{ element.position }}&lt;/td&gt;<br>      &lt;/ng-container&gt;<br><br>      &lt;!-- ... more columns ... --&gt;<br><br>      &lt;tr mat-header-row *matHeaderRowDef=&quot;displayedColumns&quot;&gt;&lt;/tr&gt;<br>      &lt;tr mat-row *matRowDef=&quot;let row; columns: displayedColumns&quot;&gt;&lt;/tr&gt;<br>    &lt;/table&gt;<br><br>    &lt;mat-paginator [length]=&quot;dataSource.data.length&quot; [pageSize]=&quot;10&quot; /&gt;<br>  `,<br>})<br>export class TestTableComponent {<br>  readonly dataSource = new MatTableDataSource&lt;Data&gt;([]);<br>  readonly paginator = viewChild(MatPaginator);<br><br>  readonly displayedColumns: string[] = [&#39;position&#39;, &#39;name&#39;, &#39;weight&#39;, &#39;symbol&#39;];<br><br>  constructor() {<br>    const data: Data[] = [];<br>    Array.from({ length: 100 }, (_, k) =&gt; k + 1).forEach(v =&gt; {<br>      data.push({ position: v, name: `E ${v}`, weight: v * 1.5, symbol: `E${v}` });<br>    });<br><br>    this.dataSource.data = data;<br><br>    afterNextRender(() =&gt; {<br>      const paginator = this.paginator();<br><br>      if (paginator) {<br>        this.dataSource.paginator = paginator;<br>      }<br>    });<br>  }<br>}</pre><p>With this simple configuration, your table looks as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OMpg5UlIgPmtrn8FtQYgCA.png" /><figcaption>Basic Table Basic Pagination</figcaption></figure><p>What we want to achieve is creating a directive that we can attach to the mat-paginator and it will transform the look of our paginated table into the bubble example. The usage of the directive will be the following:</p><pre>&lt;mat-paginator<br>  [appBubblePagination]=&quot;dataSource.data.length&quot;<br>  (page)=&quot;onPageChange($event)&quot;<br>  [length]=&quot;dataSource.data.length&quot;<br>  [pageSize]=&quot;15&quot;&gt;<br>&lt;/mat-paginator&gt;</pre><p>Here is the full code of the directive and below I describe some of its sections.</p><pre>import { Directive, ElementRef, Renderer2, afterRenderEffect, inject, input, untracked } from &#39;@angular/core&#39;;<br>import { MatPaginator } from &#39;@angular/material/paginator&#39;;<br><br>/**<br> * Works from angular-material version 15. since all classes got the new prefix &#39;mdc-&#39;<br> */<br>@Directive({<br>  selector: &#39;[appBubblePagination]&#39;,<br>})<br>export class BubblePaginationDirective {<br>  private readonly matPag = inject(MatPaginator, {<br>    optional: true,<br>    self: true,<br>    host: true,<br>  });<br>  private readonly elementRef = inject(ElementRef);<br>  private readonly ren = inject(Renderer2);<br><br>  /**<br>   * whether we want to display first/last button and dots<br>   */<br>  readonly showFirstButton = input(true);<br>  readonly showLastButton = input(true);<br><br>  /**<br>   * total number of items in pagination<br>   * needed to calculate how many buttons to render<br>   * when page size changes<br>   */<br>  readonly paginationSize = input(0, {<br>    alias: &#39;appBubblePagination&#39;,<br>  });<br><br>  /**<br>   * how many buttons to display before and after<br>   * the selected button<br>   */<br>  readonly renderButtonsNumber = input(2);<br><br>  /**<br>   * references to DOM elements<br>   */<br>  private dotsEndRef!: HTMLElement;<br>  private dotsStartRef!: HTMLElement;<br>  private bubbleContainerRef!: HTMLElement;<br><br>  /**<br>   * ref to rendered buttons on UI that we can remove them size changes<br>   */<br>  private buttonsRef: HTMLElement[] = [];<br><br>  readonly buildButtonsEffect = afterRenderEffect(() =&gt; {<br>    // rebuild buttons when pagination size change<br>    this.paginationSize();<br><br>    untracked(() =&gt; {<br>      // remove buttons before creating new ones<br>      this.removeButtons();<br><br>      // set some default styles to mat pagination<br>      this.styleDefaultPagination();<br><br>      // create bubble container<br>      this.createBubbleDivRef();<br><br>      // create all buttons<br>      this.buildButtons();<br><br>      // switch back to page 0<br>      this.switchPage(0);<br>    });<br>  });<br><br>  /**<br>   * change the active button style to the current one and display/hide additional buttons<br>   * based on the navigated index<br>   */<br>  private changeActiveButtonStyles(previousIndex: number, newIndex: number) {<br>    const previouslyActive = this.buttonsRef[previousIndex];<br>    const currentActive = this.buttonsRef[newIndex];<br><br>    if (!previouslyActive &amp;&amp; !currentActive) {<br>      return;<br>    }<br><br>    // remove active style from previously active button<br>    if (previouslyActive) {<br>      this.ren.removeClass(previouslyActive, &#39;g-bubble__active&#39;);<br>    }<br><br>    // add active style to new active button<br>    this.ren.addClass(currentActive, &#39;g-bubble__active&#39;);<br><br>    // hide all buttons<br>    this.buttonsRef.forEach(button =&gt; this.ren.setStyle(button, &#39;display&#39;, &#39;none&#39;));<br><br>    // show N previous buttons and X next buttons<br>    const renderElements = this.renderButtonsNumber();<br>    const endDots = newIndex &lt; this.buttonsRef.length - renderElements - 1;<br>    const startDots = newIndex - renderElements &gt; 0;<br><br>    const firstButton = this.buttonsRef[0];<br>    const lastButton = this.buttonsRef[this.buttonsRef.length - 1];<br><br>    // last bubble and dots<br>    if (this.showLastButton()) {<br>      this.ren.setStyle(this.dotsEndRef, &#39;display&#39;, endDots ? &#39;block&#39; : &#39;none&#39;);<br>      this.ren.setStyle(lastButton, &#39;display&#39;, endDots ? &#39;flex&#39; : &#39;none&#39;);<br>    }<br><br>    // first bubble and dots<br>    if (this.showFirstButton()) {<br>      this.ren.setStyle(this.dotsStartRef, &#39;display&#39;, startDots ? &#39;block&#39; : &#39;none&#39;);<br>      this.ren.setStyle(firstButton, &#39;display&#39;, startDots ? &#39;flex&#39; : &#39;none&#39;);<br>    }<br><br>    // resolve starting and ending index to show buttons<br>    const startingIndex = startDots ? newIndex - renderElements : 0;<br><br>    const endingIndex = endDots ? newIndex + renderElements : this.buttonsRef.length - 1;<br><br>    // display starting buttons<br>    for (let i = startingIndex; i &lt;= endingIndex; i++) {<br>      const button = this.buttonsRef[i];<br>      this.ren.setStyle(button, &#39;display&#39;, &#39;flex&#39;);<br>    }<br>  }<br><br>  /**<br>   * Removes or change styling of some html elements<br>   */<br>  private styleDefaultPagination() {<br>    const nativeElement = this.elementRef.nativeElement;<br>    const itemsPerPage = nativeElement.querySelector(&#39;.mat-mdc-paginator-page-size&#39;);<br>    const howManyDisplayedEl = nativeElement.querySelector(&#39;.mat-mdc-paginator-range-label&#39;);<br>    const previousButton = nativeElement.querySelector(&#39;button.mat-mdc-paginator-navigation-previous&#39;);<br>    const nextButtonDefault = nativeElement.querySelector(&#39;button.mat-mdc-paginator-navigation-next&#39;);<br><br>    // remove &#39;items per page&#39;<br>    if (itemsPerPage) {<br>      this.ren.setStyle(itemsPerPage, &#39;display&#39;, &#39;none&#39;);<br>    }<br><br>    // style text of how many elements are currently displayed<br>    if (howManyDisplayedEl) {<br>      this.ren.setStyle(howManyDisplayedEl, &#39;position&#39;, &#39;absolute&#39;);<br>      this.ren.setStyle(howManyDisplayedEl, &#39;color&#39;, &#39;#919191&#39;);<br>      this.ren.setStyle(howManyDisplayedEl, &#39;font-size&#39;, &#39;14px&#39;);<br>      this.ren.setStyle(howManyDisplayedEl, &#39;left&#39;, &#39;-0&#39;);<br>    }<br><br>    // check whether to remove left &amp; right default arrows<br>    this.ren.setStyle(previousButton, &#39;display&#39;, &#39;none&#39;);<br>    this.ren.setStyle(nextButtonDefault, &#39;display&#39;, &#39;none&#39;);<br>  }<br><br>  /**<br>   * creates `bubbleContainerRef` where all buttons will be rendered<br>   */<br>  private createBubbleDivRef(): void {<br>    const actionContainer = this.elementRef.nativeElement.querySelector(&#39;div.mat-mdc-paginator-range-actions&#39;);<br>    const nextButtonDefault = this.elementRef.nativeElement.querySelector(&#39;button.mat-mdc-paginator-navigation-next&#39;);<br><br>    // create a HTML element where all bubbles will be rendered<br>    this.bubbleContainerRef = this.ren.createElement(&#39;div&#39;) as HTMLElement;<br>    this.ren.addClass(this.bubbleContainerRef, &#39;g-bubble-container&#39;);<br><br>    // render element before the &#39;next button&#39; is displayed<br>    this.ren.insertBefore(actionContainer, this.bubbleContainerRef, nextButtonDefault);<br>  }<br><br>  /**<br>   * helper function that builds all button and add dots<br>   * between the first button, the rest and the last button<br>   *<br>   * end result: (1) .... (4) (5) (6) ... (25)<br>   */<br>  private buildButtons(): void {<br>    if (!this.matPag) {<br>      return;<br>    }<br><br>    const neededButtons = Math.ceil(this.matPag.length / this.matPag.pageSize);<br><br>    // if there is only one page, do not render buttons<br>    if (neededButtons === 0 || neededButtons === 1) {<br>      this.ren.setStyle(this.elementRef.nativeElement, &#39;display&#39;, &#39;none&#39;);<br>      return;<br>    }<br><br>    // set back from hidden to block<br>    this.ren.setStyle(this.elementRef.nativeElement, &#39;display&#39;, &#39;block&#39;);<br><br>    // create first button<br>    this.buttonsRef = [this.createButton(0)];<br><br>    // add dots (....) to UI<br>    this.dotsStartRef = this.createDotsElement();<br><br>    // create all buttons needed for navigation (except the first &amp; last one)<br>    for (let index = 1; index &lt; neededButtons - 1; index++) {<br>      this.buttonsRef = [...this.buttonsRef, this.createButton(index)];<br>    }<br><br>    // add dots (....) to UI<br>    this.dotsEndRef = this.createDotsElement();<br><br>    // create last button to UI after the dots (....)<br>    this.buttonsRef = [...this.buttonsRef, this.createButton(neededButtons - 1)];<br>  }<br><br>  /**<br>   * Remove all buttons from DOM<br>   */<br>  private removeButtons(): void {<br>    this.buttonsRef.forEach(button =&gt; {<br>      this.ren.removeChild(this.bubbleContainerRef, button);<br>    });<br><br>    // remove dots<br>    if (this.dotsStartRef) {<br>      this.ren.removeChild(this.bubbleContainerRef, this.dotsStartRef);<br>    }<br>    if (this.dotsEndRef) {<br>      this.ren.removeChild(this.bubbleContainerRef, this.dotsEndRef);<br>    }<br><br>    // Empty state array<br>    this.buttonsRef.length = 0;<br>  }<br><br>  /**<br>   * create button HTML element<br>   */<br>  private createButton(i: number): HTMLElement {<br>    const bubbleButton = this.ren.createElement(&#39;div&#39;);<br>    const text = this.ren.createText(String(i + 1));<br><br>    // add class &amp; text<br>    this.ren.addClass(bubbleButton, &#39;g-bubble&#39;);<br>    this.ren.setStyle(bubbleButton, &#39;margin-right&#39;, &#39;8px&#39;);<br>    this.ren.appendChild(bubbleButton, text);<br><br>    // react on click<br>    this.ren.listen(bubbleButton, &#39;click&#39;, () =&gt; {<br>      this.switchPage(i);<br>    });<br><br>    // render on UI<br>    this.ren.appendChild(this.bubbleContainerRef, bubbleButton);<br><br>    // set style to hidden by default<br>    this.ren.setStyle(bubbleButton, &#39;display&#39;, &#39;none&#39;);<br><br>    return bubbleButton;<br>  }<br><br>  /**<br>   * helper function to create dots (....) on DOM indicating that there are<br>   * many more bubbles until the last one<br>   */<br>  private createDotsElement(): HTMLElement {<br>    const dotsEl = this.ren.createElement(&#39;span&#39;);<br>    const dotsText = this.ren.createText(&#39;.....&#39;);<br><br>    // add class<br>    this.ren.setStyle(dotsEl, &#39;font-size&#39;, &#39;18px&#39;);<br>    this.ren.setStyle(dotsEl, &#39;margin-right&#39;, &#39;8px&#39;);<br>    this.ren.setStyle(dotsEl, &#39;padding-top&#39;, &#39;6px&#39;);<br>    this.ren.setStyle(dotsEl, &#39;color&#39;, &#39;#919191&#39;);<br><br>    // append text to element<br>    this.ren.appendChild(dotsEl, dotsText);<br><br>    // render dots to UI<br>    this.ren.appendChild(this.bubbleContainerRef, dotsEl);<br><br>    // set style none by default<br>    this.ren.setStyle(dotsEl, &#39;display&#39;, &#39;none&#39;);<br><br>    return dotsEl;<br>  }<br><br>  /**<br>   * Helper function to switch page<br>   */<br>  private switchPage(i: number): void {<br>    if (!this.matPag) {<br>      return;<br>    }<br><br>    const previousPageIndex = this.matPag.pageIndex;<br><br>    // switch page index of mat paginator<br>    this.matPag.pageIndex = i;<br><br>    // change active button styles<br>    this.changeActiveButtonStyles(previousPageIndex, this.matPag.pageIndex);<br><br>    // need to trigger page event manually, because we are changing pageIndex programmatically<br>    this.matPag.page.emit({<br>      pageIndex: i,<br>      pageSize: this.matPag.pageSize,<br>      length: this.matPag.length,<br>      previousPageIndex: previousPageIndex,<br>    });<br>  }<br>}</pre><h3>Injecting Dependencies</h3><pre>inject(MatPaginator, { optional: true, self: true, host: true })<br>inject(ElementRef)<br>inject(Renderer2)</pre><ul><li>MatPaginator - we hook into its current pageIndex, pageSize, and its page stream</li><li>ElementRef - root element of the paginator (so we can query its internals)</li><li>Renderer2 - the safe way to create elements, set styles/classes, and listen to events. Works nicely with SSR and avoids direct DOM APIs</li></ul><h3>Input / Output Bindings</h3><ul><li>showFirstButton = input(true); &amp; showLastButton = input(true); - whether to display first and last buttons for fast navigation on the start / end of the table</li><li>renderButtonsNumber = input(2); - when you are on an active page, let’s say index 6 , then how many buttons before and after should we display</li><li>paginationSize - this input is required to detect changes in the table length (after filtering or loading new data). When it changes, the directive re-renders the bubbles to match the correct number of pages</li></ul><h3>Core Logic Execution</h3><p>The directive itself is around 300 lines of code, but when you try to understand how it works, the main logic is inside the buildButtonsEffect effect, such as:</p><pre>readonly buildButtonsEffect = afterRenderEffect(() =&gt; {<br>  // rebuild buttons when pagination size change<br>  this.paginationSize();<br><br>  untracked(() =&gt; {<br>    // remove buttons before creating new ones<br>    this.removeButtons();<br><br>    // set some default styles to mat pagination<br>    this.styleDefaultPagination();<br><br>    // create bubble container<br>    this.createBubbleDivRef();<br><br>    // create all buttons<br>    this.buildButtons();<br><br>    // switch back to page 0<br>    this.switchPage(0);<br>  });<br>});</pre><p>What is great about the effect, is that, it will re-execute when length (size) of the elements change, so for example if you have one table, but doing server-side data filtering, then each time new data arrives, bubbles will be recalculated due to paginationSize signal input. The brief overview is described below.</p><ul><li>paginationSize - listen on page size changes (on new data) to recalculate bubbles</li><li>removeButtons() – clear previous custom DOM (if re-running)</li><li>styleDefaultPagination() – hide certain default Material bits and position labels</li><li>createBubbleDivRef() – create a container where our bubbles will live</li><li>buildButtons() – create bubbles + dots based on total length and page size</li><li>switchPage(0) – start from page 0 to keep things predictable</li></ul><p>You may also ask, why we use afterRenderEffect instead of effect ? The reason is that afterRenderEffect is executed only in the browser, but effect also runs on the server side. It could lead to some errors if your app supports SSR. For a deeper explanation, check out my <a href="https://www.angularspace.com/afterrendereffect-afternextrender-aftereveryrender-renderer2/">afterRenderEffect, afterNextRender, afterEveryRender &amp; Renderer2 article</a>.</p><h3>Core Logic Execution — Switching Page Manually</h3><p>The custom bubbles live outside Angular Material’s built-in controls. That means when a user clicks a bubble, nothing in MatPaginator fires by itself, we have to connect the click to the paginator so the table (and anyone subscribed to matPag.page) reacts, hence the need for switchPage() function.</p><pre>private createButton(index: number): HTMLElement {<br>  // our unique bubble showing a specific page - 1, 2, etc.<br>  const bubbleButton = this.ren.createElement(&#39;div&#39;);<br><br>  // ... some code ...<br><br>  this.ren.listen(bubbleButton, &#39;click&#39;, () =&gt; {<br>    this.switchPage(index);<br>  });<br><br>  // ... some code ...<br>}<br><br>private switchPage(index: number): void {<br>  if (!this.matPag) {<br>    return;<br>  }<br><br>  const previousPageIndex = this.matPag.pageIndex;<br><br>  // switch page index of mat paginator<br>  this.matPag.pageIndex = index;<br><br>  // change active button styles<br>  this.changeActiveButtonStyles(previousPageIndex, this.matPag.pageIndex);<br><br>  // trigger page event manually, we are changing index programmatically<br>  this.matPag.page.emit({<br>    pageIndex: index,<br>    pageSize: this.matPag.pageSize,<br>    length: this.matPag.length,<br>    previousPageIndex: previousPageIndex,<br>  });<br>}</pre><p>The key part of is this.matPag.pageIndex = index;, keeping the paginator’s internal state in sync with witch bubble was clicked. If you were to remove this line, the pagination would stop working.</p><p>Next, since we are programmatically changing the index of the paginator (mentioned above), when you navigate though the items in the table, the this.matPag.page will not emit by itself, therefore we also need to manually emit this data.</p><h3>Paginator Style Updates</h3><p>Inside styleDefaultPagination, you can see we’re directly accessing the paginator’s internal HTML elements to restyle them. Is this ideal? Probably not. Since it relies on exact class selectors like button.mat-mdc-paginator-navigation-next, it’s fragile. These internal selectors can change between Material versions.</p><p>This already happened when Material v15 introduced the new MDC components, which broke custom styling for many projects using ::ng-deep. What we’re doing here is a similar kind of hack, but for our use case it’s the most practical solution available. Still, it’s worth being aware of the tradeoff.</p><h3>Custom Styles</h3><p>Once the logic is done, we still need some styling to make it actually look like bubbles. This part is mostly CSS (or SCSS), and you can adjust it to fit your own theme. In my example, each bubble is a simple flex container with centered text, a hover state, and an active state to highlight the current page.</p><pre>/* Custom paginator styles */<br>.g-bubble-container {<br>  display: flex;<br>  gap: 4px;<br>}<br><br>.g-bubble {<br>  background-color: #f0f0f0;<br>  border-radius: 50%;<br>  width: 34px;<br>  height: 34px;<br>  display: flex;<br>  align-items: center;<br>  justify-content: center;<br>  color: #2e2e2e;<br>  font-size: 14px;<br>  cursor: pointer;<br>  transition: 0.3s;<br><br>  &amp;:hover {<br>    background-color: #636363;<br>    color: orange;<br>  }<br>}<br><br>.g-bubble__active {<br>  background-color: #636363;<br>  color: orange;<br>}<br><br>mat-paginator {<br>  background: transparent !important;<br>  /* need mat-paginator range to align with other mat-table elements */<br>  position: relative;<br>}<br><br>/* override alignment for the labels that shows &quot;x of y&quot; */<br>.mat-mdc-paginator-range-label {<br>  margin: 0 !important;<br>}</pre><h3>Things to Keep in Mind</h3><p>There are a few small details that are good to keep in mind:</p><ul><li>Renderer2 limitations — you can’t directly use pseudo-classes (::before, ::after) from within the directive, keep your visual parts inside SCSS files</li><li>Changing Angular Material internals — as mentioned earlier, mat-mdc- selectors can change in future Material versions, it’s one of the risks of this directive</li><li>Accessibility (a11y) — since these are custom clickable divs, you might want to add role=&quot;button&quot; and tabindex=&quot;0&quot; attributes so users can navigate the bubbles with a keyboard. You can also listen for keydown events and simulate click behavior with the space or enter key</li><li>SSR / Hydration — if you’re running Angular SSR, the directive should still work fine, since Renderer2 is SSR safe and we are using afterRenderEffect to render bubbles only on the client-side</li><li>Active Button State — currently when we load more data into the table and re-execute the logic of rendering bubbles, we go back to the first page, so no active state was implemented yet</li><li>Important input [appBubblePaginationLength] to bound the table length. Without it, the afterRenderEffect will not be notified that new data have arrived and buttons will not be rebuilt</li></ul><h3>Summary</h3><p>By the end of this post, you should have a working, MDC compatible paginator. The goal here wasn’t to replace Angular Material, but to show how far you can go using directives + Renderer2, to enhance an existing Material component, without creating your own custom paginator from scratch.</p><p>Of course there may be some room for improvement, it is still a simple directive, so if you have any suggestions, feel free to comment. Hope you liked this example, catch more of my articles on <a href="https://dev.to/krivanek06">dev.to</a>, connect with me on <a href="https://www.linkedin.com/in/eduard-krivanek">LinkedIn</a> or check my <a href="https://eduardkrivanek.com/">Personal Website</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa91e697fd88" width="1" height="1" alt=""><hr><p><a href="https://medium.com/multitude-it-labs/angular-custom-matpaginator-styling-fa91e697fd88">Angular — Custom MatPaginator Styling</a> was originally published in <a href="https://medium.com/multitude-it-labs">Multitude IT Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build A Full-Stack Application With AnalogJS]]></title>
            <link>https://medium.com/multitude-it-labs/build-a-full-stack-application-with-analogjs-efa137a1b59e?source=rss----5c76af6b2fa7---4</link>
            <guid isPermaLink="false">https://medium.com/p/efa137a1b59e</guid>
            <category><![CDATA[analog-js]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Eduard Krivanek]]></dc:creator>
            <pubDate>Mon, 05 May 2025 08:11:18 GMT</pubDate>
            <atom:updated>2025-05-05T08:23:43.487Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*voyZp6ROfNhZTcqQVrbK_A.png" /></figure><p>You’ve probably heard the Vue crowd singing praises about Nuxt, and the React folks wouldn’t dare start a project without Next.js. Meanwhile, over in Angular land, we were kinda missing out on that meta-framework magic. Or we did, until <a href="https://github.com/brandonroberts">Brandon Roberts</a> stepped in with <a href="https://analogjs.org/">AnalogJS</a>, attempting to bring those same modern features to Angular.</p><p>I’d heard about AnalogJS a bunch of times, so as an Angular developer, I had to give it a shot. I rebuilt my personal website, <a href="https://eduardkrivanek.com/">eduardkrivanek.com</a> (shameless plug), switching it from React 😱 to Angular 😎. But slapping together a blog-style app wasn’t enough. I wanted to see if Analog could handle the demands of a full-stack application.</p><p>In this post, I’ll walk you through some of the features Analog offers by building an anime search app. Think of this article as a summary of what AnalogJS is capable of. I will go over how I created this small application, but I highly recommend reading the <a href="https://analogjs.org/docs">official docs</a>. The presented project is available <a href="https://github.com/krivanek06/analogjs-example-project">on GitHub</a>. This example uses Angular 19.2 and AnalogJS 1.15.1. Here is GIF about the final result that we will be. Blog was originally published on <a href="https://www.angularspace.com/build-a-full-stack-application-with-analogjs/">angular-spaces</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qCG7oVDyG5_d45HcgxT6yA.gif" /><figcaption>Application Overview</figcaption></figure><h3>Getting Started</h3><p>So, what even is AnalogJS, and why should you care? Well, I’d say it’s worth checking out if:</p><ol><li>You’re building a full-stack app and don’t want separate backend</li><li>You’re aiming for SSR/SSG-heavy pages and want that SEO optimization</li></ol><p>The features which Analog provides (and what I’ll cover throughout this post) are:</p><ul><li>File-based routing</li><li>Route metadata</li><li>API routes</li><li>SSR + SSG rendering</li><li>Form Actions</li><li>Vite (instead of Angular CLI)</li><li>Markdown content support (like Nuxt Content)</li><li>Full-stack capabilities (API + frontend in one)</li></ul><p>To get started with Analog use the command npm create analog@latest or if you already have an existing project, and want to migrate to analog, you can follow their <a href="https://analogjs.org/docs/guides/migrating">migration guide</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r85o1BArnCe58As3bAe_xA.png" /><figcaption>Project Generation</figcaption></figure><p>For my example you will see that I opted-out from <a href="https://analogjs.org/docs/experimental/sfc">Analog’s SFC</a>, which is the “svelte-like” syntax, however this is all personal preference. Another optional thing, in new projects, is removing zonje.js following <a href="https://angular.dev/guide/experimental/zoneless">Angular’s guideline</a> for the best performance.</p><h3>Application Routing Overview</h3><p>The example app makes use of all the routing features Analog offers, including static routes, dynamic routes, layout routes, and route groups. We’ll break each of these down in more detail later, but for now, here’s the folder structure we’re working with:</p><pre>src/<br>└── app/<br>    └── pages/<br>        |── (anime)/<br>        │   ├── details.[animeId].page.ts<br>        │   ├── my-list.page.ts        <br>        ├── (auth)/<br>        │   ├── login.page.ts<br>        │   ├── login.server.ts        <br>        │   ├── register.page.ts<br>        │   └── register.server.ts        <br>        ├── (blog)/<br>        │   └── [slug].page.ts<br>        ├── (auth).page.ts<br>        ├── [...page-not-found].page.ts<br>        ├── index.page.ts</pre><p>First we start with the main index.page.ts that is served on the initial / route. Next, if the user somehow wanders into a non-existing route, the [...page-not-found].page.ts component will catch all of them. It represents a wildcard ** route.</p><p>For authentication, we’ve got login and register pages living inside the (auth) folder. This folder doesn’t change the actual routing, it’s just there to keep things together. We also added (auth).page.ts to provide a shared layout for those two pages. The login.server.ts and register.server.ts files are where form actions happen, but more on those later.</p><p>Our blog section is handled by (blog)/[slug].page.ts, which maps to URLs like /blog1, /blog2, and so on. It’s a dynamic route used for rendering content pages.</p><p>When someone searches and clicks on an anime, the details appear at /details/123, with 123 being the anime’s ID. This page is public and server-side rendered. Logged-in users can also create their own favorites list at /my-list. Since that’s a private page, it’s rendered entirely on the client side.</p><h3>Application Routing Detailed</h3><p>With this section I want to go a bit deeper how each route works, reading route parameters, how to configure rendering and setting metadata.</p><h3>Static Routes</h3><p>A route is considered static if there are no square brackets [] in the filename. In our case, the / and /my-list routes are static and look something like this (with a richer template):</p><pre>@Component({<br>  template: `&lt;h2&gt;Home Page&lt;/h2&gt;`,<br>})<br>export default class HomePageComponent {}</pre><p>What I learnt is that selectors (selector: &#39;app-home&#39;) have no effect on the page components, you can skip them and the component name is also irrelevant. We are using the HomePageComponent name, however you can name it BananaComponent and the final result will stay the same. What actually matters is where the file lives inside the /app/pages folder structure.</p><p>Worth to mention to not forget the default keyword when defining a route, otherwise you can get the NG04014: Invalid configuration of route &#39;&#39; error.</p><h3>Dynamic Routes</h3><p>Dynamic routes are defined by their filename, where the route param is inside the square brackets. In our example, when a user navigates to /details/123, the details.[animeId].page.ts component kicks in and loads data based on the animeId value.</p><pre>@Component({ template: `...` })<br>export default class AnimeDetailsPageComponent {<br>  private readonly route = inject(ActivatedRoute);<br>  private readonly animeApiService = inject(AnimeApiService);<br><br> readonly animeDetails = rxResource({<br>    loader: () =&gt;<br>      this.route.paramMap.pipe(<br>        map(params =&gt; params.get(&#39;animeId&#39;)),<br>        filter((animeId): animeId is string =&gt; !!animeId),<br>        switchMap(animeId =&gt; this.animeApiService.getAnimeById(animeId))<br>      ),<br>  });<br>}</pre><h3>Layout Routes</h3><p>Layout routes are created by setting up a parent file and a child folder with the same name. In our case, we have the (auth).page.ts parent component, and inside the (auth) folder, we have the login.page.ts and register.page.ts pages as its children. To make the layout work, the parent (auth).page.ts needs to include a router-outlet to render its child routes, like this:</p><pre>@Component({<br>  imports: [RouterOutlet, RouterLink],<br>  template: ` <br>    &lt;h2&gt;Auth Layout&lt;/h2&gt;<br><br>    &lt;button type=&quot;button&quot; routerLink=&quot;/login&quot;&gt;login&lt;/button&gt;<br>    &lt;button type=&quot;button&quot; routerLink=&quot;/register&quot;&gt;register&lt;/button&gt;<br><br>    &lt;router-outlet /&gt;<br>   `,<br>})<br>export default class AuthLayoutComponent {}</pre><h3>Catch-All Routes</h3><p>This route was defined by [...page-not-found].page.ts, as it represents the wildcard **. The following example is from the <a href="https://analogjs.org/docs/features/routing/overview#catch-all-routes">official docs</a>:</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { RouterLink } from &#39;@angular/router&#39;;<br>import { injectResponse } from &#39;@analogjs/router/tokens&#39;;<br>import { RouteMeta } from &#39;@analogjs/router&#39;;<br><br>export const routeMeta: RouteMeta = {<br>  title: &#39;Page Not Found&#39;,<br>  canActivate: [() =&gt; {<br>      const response = injectResponse();<br>      if (import.meta.env.SSR &amp;&amp; response) {<br>        response.statusCode = 404;<br>        response.end();<br>      }<br>      return true;<br>  }],<br>};<br><br>@Component({<br>  imports: [RouterLink],<br>  template: `&lt;a routerLink=&quot;/&quot;&gt;Go Back Home&lt;/a&gt;`,<br>})<br>export default class PageNotFoundComponent {}</pre><p>The routeMeta is set up so that if you type a non-existent URL like /nonexistingroute and hit enter, the request goes through SSR by default. But thanks to routeMeta, the server won’t even try to render that page, it just returns a 404 right away. However, if you navigate to a non-existing route from within the app (like via a button click), it falls back to client-side rendering and shows a friendly &quot;go back home&quot; message instead.</p><h3>Route Metadata</h3><p>Another great use case for <a href="https://analogjs.org/docs/features/routing/metadata">route metadata</a> is SEO and optimizing how your pages appear on social platforms. If you’re new to that, the <a href="https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Structuring_content/Webpage_metadata">MDN guide on webpage metadata</a> is a super helpful starting point. Here’s a quick example:</p><pre>export const routeMeta: RouteMeta = {<br>  meta: [<br>    {<br>      name: &#39;author&#39;,<br>      content: &#39;Eduard Krivanek&#39;,<br>    },<br>    {<br>      property: &#39;og:title&#39;,<br>      content: &#39;Anime Search&#39;,<br>    },<br>    {<br>      property: &#39;og:description&#39;,<br>      content: &#39;Example App about anime search&#39;,<br>    },<br>  ]};<br><br>@Component({ template: `` })<br>export default class HomeComponent {}</pre><h3>Rendering Strategy</h3><p>By default, every page in Analog uses SSR to generate content. But <a href="https://analogjs.org/docs/features/server/static-site-generation">Analog also supports SSG</a>, and you can even opt out completely and go with CSR. The <a href="https://www.freecodecamp.org/news/server-side-rendering-javascript/">SSR vs CSR article</a> is a solid read if you are wondering when to use what.</p><p>In our case, we use SSR for the / route, the homepage, since it fetches anime data right away and benefits from that initial server render. The /my-list page, however, is behind an auth wall, so SEO isn&#39;t really a concern. That raises the question: “Should I bother with SSR here?” Personally, I’d say no. For dashboard-style pages, CSR usually does the job just fine.</p><p>Then we’ve got /login, /register, and all the blog pages. These don’t change often, so they’re perfect candidates for SSG. To achieve this configuration, you’ll need to adjust the plugins section in your vite.config.ts.</p><pre>plugins: [<br>    analog({<br>      prerender: {<br>        routes: async () =&gt; [<br>          &#39;/login&#39;,<br>          &#39;/register&#39;,<br>          {<br>            contentDir: &#39;src/content/blog&#39;,<br>            transform: file =&gt; {<br>              const slug = file.attributes?.[&#39;slug&#39;] || file.name;<br>              return `/blog/${slug}`;<br>            },<br>          },<br>        ],<br>      },<br>      nitro: {<br>        routeRules: {<br>          &#39;/my-list&#39;: { ssr: false },<br>        },<br>      },<br>    }),<br>  ],</pre><p>Worth mentioning that even if you leave some pages to be rendered by SSR, you can still use @defer (on viewport){} to load child components, such as charts, or mainly components which work with DOM, only the client side. For that read more about <a href="https://angular.dev/guide/templates/defer">defer syntax from Angular docs</a>.</p><h3>Markdown Content Generation</h3><p>One feature I really appreciate as a blog-posting human is <a href="https://analogjs.org/docs/features/routing/content">markdown content support</a> in Analog. For our app, we want to display three blog posts, which we’ll store in /src/content/blog. We want to set up routing, render the posts, add formatting, and even dynamic route metadata.</p><p>First step it to open src/app/app.config.ts, enable markdown file support, and add a syntax highlighter. You can pick between <a href="https://prismjs.com/">Prism</a> or <a href="https://shiki.matsu.io/">Shiki</a>, both are great, but for this example, we’re rolling with Prism.</p><pre>// src/app/app.config.ts<br>import { ApplicationConfig } from &#39;@angular/core&#39;;<br>import { provideContent, withMarkdownRenderer } from &#39;@analogjs/content&#39;;<br>import { withPrismHighlighter } from &#39;@analogjs/content/prism-highlighter&#39;;<br><br>export const appConfig: ApplicationConfig = {<br>  providers: [<br>    // ... other providers<br>    provideContent(withMarkdownRenderer(), withPrismHighlighter()),<br>  ],<br>};</pre><p>When it comes to markdown files (in the /src/content/blog folder), it’s way easier to keep all your blog posts in a single folder, instead of creating a new folder for each post. Before listing out the blogs, you’ll probably want to add some metadata to each file, like this:</p><pre>---<br>title: &#39;Test Blog 1&#39;<br>tags: angular, rxjs<br>order: 1<br>datePublished: 01.01.2024<br>coverImage: article-cover/background.jpg<br>---<br><br>## Lorem Ipsum<br>&quot;Neque porro quisquam est qui dolorem...&quot;</pre><p>You can access the <a href="https://analogjs.org/docs/features/routing/content#using-the-content-files-list">content file list</a> by the injectContentFiles function, that takes a filter where you pass in the location of your content, in our case the /src/content/blog folder.</p><pre>import { injectContentFiles } from &#39;@analogjs/content&#39;;<br><br>@Component({<br>  imports: [RouterLink],<br>  template: `<br>    @for (post of posts; track post.attributes.title) {<br>      &lt;div [routerLink]=&quot;[&#39;/blog&#39;, post.slug]&quot;&gt;<br>        Blogpost - {{ post.attributes.title }}<br>      &lt;/div&gt;<br>    }<br>`})<br>export default class HomeComponent {<br>  readonly posts = injectContentFiles&lt;{<br>    title: string;<br>    tags: string;<br>    datePublished: string;<br>    coverImage: string;<br>  }&gt;(files =&gt; files.filename.includes(&#39;/src/content/blog&#39;));<br>}</pre><p>The post.slug is simply the filename of your blog post. So if a user clicks on test-blog-1.md, they’ll be taken to /blog/test-blog-1, and the blog/[slug].page.ts route will catch and render it.</p><p>To display the content of the blogpost, inside the blog/[slug].page.ts route, analog provides the injectContent function and a MarkdownComponent to display the blogpost in a formatted way.</p><pre>@Component({<br>  imports: [AsyncPipe, MarkdownComponent],<br>  template: `<br>    @if (post$ | async; as post) {<br>      &lt;article class=&quot;prose prose-slate&quot;&gt;<br>        &lt;img [src]=&quot;post.attributes.coverImage&quot; /&gt;<br>        &lt;analog-markdown [content]=&quot;post.content&quot; /&gt;<br>      &lt;/article&gt;<br>    }<br> `,<br>})<br>export default class BlogPostComponent {<br>  readonly post$ = injectContent&lt;{<br>    title: string;<br>    tags: string;<br>    datePublished: string;<br>    coverImage: string;<br>  }&gt;({<br>    param: &#39;slug&#39;,<br>    subdirectory: &#39;blog&#39;,<br>  });<br>}</pre><p>At this point the markdown may be rendered, but styles will not be applied. To fix that, you need to import prismjs styles. If you’re using Tailwind, you’ll also want to add <a href="https://github.com/tailwindlabs/tailwindcss-typography">tailwindcss-typography</a> for that extra polish (and apply the prose css class where you rendered the blogs). Depending on your Tailwind version (mine’s 4+), you’ll need to edit your style.css.</p><pre>/* Tailwind directives  */<br>@import &#39;tailwindcss&#39;;<br><br>@import &#39;prismjs/plugins/toolbar/prism-toolbar.css&#39;;<br>/* check node_modules/prismjs/themes/ for the available themes */<br>@import &#39;prismjs/themes/prism-tomorrow&#39;;<br>/* highlight text for markdown */<br>@plugin &quot;@tailwindcss/typography&quot;;</pre><p>Lastly, if you’re heavy on code snippets in your markdown and notice some languages (like SQL, GraphQL, etc.) aren’t styled properly, you’ll need to update the vite.config.ts file. Just add them under content.prismOptions.additionalLangs, like so:</p><pre>// vite.config.ts<br>export default defineConfig(({ mode }) =&gt; ({<br>  plugins: [<br>    analog({<br>      content: {<br>        prismOptions: {<br>          additionalLangs: [&#39;yaml&#39;, &#39;sql&#39;, &#39;graphql&#39;, &#39;bash&#39;],<br>        },<br>      },<br>      prerender: { /* ... */ },<br>      nitro: { { /* ... */ },<br>    }),<br>  ],</pre><h3>Markdown Content Meta Tags</h3><p>The blog/[slug].page.ts is a generic component that handles rendering every markdown file living in /src/content/blog. But we also want to add some dynamic meta tags when we prerender these pages for better SEO.</p><p>If you want a deeper dive, I recommend checking out <a href="https://github.com/analogjs/analog/blob/beta/apps/blog-app/src/app/pages/blog/resolvers.ts">Brandon’s example on GitHub</a>. For our case though, we can keep it simple with the following setup:</p><pre>// src/app/pages/blog/[slug].page.ts <br>export const routeMeta: RouteMeta = {<br>  title: &#39;Blog Post&#39;,<br>  meta: route =&gt; {<br>    const file = injectContentFiles&lt;{<br>      title: string;<br>      tags: string;<br>      datePublished: string;<br>      coverImage: string;<br>    }&gt;().find(file =&gt; file.slug === route.params[&#39;slug&#39;])!;<br><br>    return [{<br>        name: &#39;author&#39;,<br>        content: &#39;Eduard Krivanek&#39;,<br>      },<br>      {<br>        property: &#39;og:title&#39;,<br>        content: file.attributes.title,<br>      },<br>      {<br>        property: &#39;og:published&#39;,<br>        content: file.attributes.datePublished,<br>      }];<br>  },<br>};<br>@Component({ template: `...`})<br>export default class BlogPostComponent { /* ... */ }</pre><p>This configuration will automatically inject the correct meta tags into each prerendered blog page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1uqy2nHe9snLaIKRDnYN_Q.png" /><figcaption>Dynamic Metatags On A Blog Page</figcaption></figure><h3>API routes</h3><p>Each app needs a database connection to persist data. In our demo app I mocked this database, but the idea remains the same. We’ve got one singleton service (class) that stores all the application data.</p><pre>export class Database {<br>  static instance = new Database();<br><br>  storedData = {};<br><br>  async createUser(username: string) { /*  */ }<br>  async addLikedAnime(username: string, anime: AnimeDetails) { /*  */ }<br>  async removeLikedAnime(username: string, animeId: number) { /*  */ }<br>}</pre><p>You’ll access every method via Database.instance.XYZ. Now, what we want to do is create an endpoint based on the <a href="https://analogjs.org/docs/features/api/overview#specific-http-request-method">HTTP request method</a>. This endpoint will allow us to pass information, like when a user marks an anime as a favorite and wants to keep it in their &quot;favourites&quot; section, then even display it on the (anime)/my-list page.</p><p>To create this endpoint, we’ll use the defineEventHandler function. This function will be placed in src/server/routes/api/anime/save-anime.post.ts with the following logic.</p><p>One thing to note is the .post suffix in save-anime.post.ts. This suffix tells Analog to create a specific HTTP POST endpoint. If you removed the .post and kept the file as save-anime.ts, this endpoint would accept any HTTP method. In our case, we want to restrict it to just POST requests.</p><pre>// src/server/routes/api/anime/save-anime.post.ts<br>import { createError, defineEventHandler, readBody } from &#39;h3&#39;;<br>import { AnimeDetails } from &#39;./../../../api/api.model&#39;;<br>import { Database } from &#39;./../../../database/database&#39;;<br><br>export default defineEventHandler(async event =&gt; {<br>  const body = (await readBody(event));<br>  const id = parseInt(body?.id);<br>  const username = body?.username;<br><br>  // check if id is a number<br>  if (!Number.isInteger(id) || !username) {<br>    throw createError({<br>      statusCode: 400,<br>      statusMessage: &#39;Invalid input data&#39;,<br>    });<br>  }<br><br>  // fetch anime details from API<br>  const response = await fetch(`https://api.jikan.moe/v4/anime/${id}`);<br>  const anime = (await response.json()) as { data: AnimeDetails };<br><br>  // save anime to DB<br>  await Database.instance.addLikedAnime(username, anime.data);<br><br>  // return liked anime to the user<br>  return { data: anime.data };<br>});</pre><p>For POST requests, the readBody function will let you access the message body. If you were using a GET request, you’d use getRouterParam instead. To send data to this backend listener, you’ll need to use HttpClient and target the /api/anime/save-anime URL.</p><pre>@Injectable({ providedIn: &#39;root&#39; })<br>export class AnimeApiService {<br>  private readonly http = inject(HttpClient);<br><br>  saveAnime(id: number | string, username: string) {<br>    return this.http.post(&#39;/api/anime/save-anime&#39;, {<br>      id,<br>      username,<br>    });<br>  }<br>}</pre><h3>API Route Protection</h3><p>Analog supports <a href="https://analogjs.org/docs/features/routing/middleware">server-side middleware</a>, designed to modify requests, sending redirects or checking for authentication. In our example we can use middleware to setup route protection on every /api/anime route, verifying if user is authenticated. Each middleware run in order defined in the /server/middleware folder.</p><pre>// /server/middleware/is-logged-in.ts<br>import { defineEventHandler, getHeader, getRequestURL, sendRedirect } from &#39;h3&#39;;<br><br>export default defineEventHandler(async event =&gt; {<br>  if (getRequestURL(event).pathname.includes(&#39;/api/anime&#39;)) {<br>    const authToken = getHeader(event, &#39;authToken&#39;);<br><br>    // check auth and redirect<br>    if (!authToken) {<br>      console.log(&#39;User not logged in, redirecting to login&#39;);<br>      sendRedirect(event, &#39;/login&#39;, 401);<br>    }<br>  }<br>});</pre><p>You either add a header to each request or create an interceptor for that, however right now if you target the /api/anime endpoint without the authToken information, you will get the following error message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PRcCgvBTNdlq4XZqWTGPMQ.png" /><figcaption>Authentication Middleware</figcaption></figure><h3>Form Actions</h3><p>Analog comes with <a href="https://analogjs.org/docs/guides/forms">form actions</a>, which allow you to handle form submissions directly, without needing a separate HTTP route to process the data (as we did earlier). Instead, the logic is placed right next to the file where the form is submitted.</p><p>The FormAction directive, imported from @analogjs/router, gives you access to onSuccess and onError event emitters on the &lt;form&gt; tag. To demonstrate this, we’ll use the (auth)/login.page.ts to handle user sign-in. The client-side component looks like this:</p><pre>@Component({<br>  imports: [FormAction, /* .... */],<br>  template: `<br>    &lt;form method=&quot;post&quot; (onSuccess)=&quot;onSuccess($event)&quot; (onError)=&quot;onError($event)&quot;&gt;<br>      &lt;mat-form-field&gt;<br>        &lt;mat-label&gt;Username&lt;/mat-label&gt;<br>        &lt;input name=&quot;username&quot; [formControl]=&quot;loginForm.controls.username&quot; /&gt;<br>      &lt;/mat-form-field&gt;<br><br>      &lt;button [disabled]=&quot;loginForm.invalid&quot;&gt;Login&lt;/button&gt;<br>    &lt;/form&gt;<br>  `,<br>})<br>export default class LoginComponent {<br>  readonly loginForm = new FormGroup({<br>    username: new FormControl(&#39;testname&#39;, {<br>      validators: [Validators.required],<br>    }),<br>  });<br><br>  onSuccess(data: unknown) {<br>    console.log(&#39;success&#39;, data as AuthUser);<br>  }<br><br>  onError(result?: unknown) {<br>    console.log(&#39;error&#39;, result);<br>  }<br>}</pre><p>To handle form submissions, you create a .server.ts alongside the .page.ts component. So, in our case, the folder structure looks like this:</p><pre>src/<br>└── app/<br>    └── pages/     <br>        ├── (auth)/<br>        │   ├── login.page.ts<br>        │   └── login.server.ts<br>        │   └── register.page.ts<br>        │   └── register.server.ts</pre><p>And inside the login.server.ts you may have a logic similar to this</p><pre>import { fail, json, type PageServerAction } from &#39;@analogjs/router/server/actions&#39;;<br>import { readFormData } from &#39;h3&#39;;<br>import { Database } from &#39;../../../server/database/database&#39;;<br><br>export async function action({ event }: PageServerAction) {<br>  const body = await readFormData(event);<br>  const username = body.get(&#39;username&#39;) as string;<br><br>  if (!username) {<br>    return fail(422, { username: &#39;Username is required&#39; });<br>  }<br><br>  if (!(await Database.instance.getUser(username))) {<br>    return fail(422, { username: &#39;Invalid username&#39; });<br>  }<br><br>  return json({ type: &#39;success&#39;, token: &#39;XYZ&#39;, username: username });<br>}</pre><p>An interesting thing I noticed is that onSuccess fires when the user authenticates successfully, but the response is always returned as an unknown type. So, if you try to write onSuccess(data: AuthUser) {}, you’ll get an error: Argument of type &#39;unknown&#39; is not assignable to parameter of type &#39;AuthUser&#39;. You could validate the data using Zod, or as shown in the example, just cast it to the right type manually.</p><p>In the LoginComponent, we used FormGroup to build the form. However, with form actions, this isn&#39;t strictly necessary. You just need to display the form fields in the UI, assign a unique name to each one, and when the form is submitted, it will send the data using method=&quot;post&quot; to the form handler. The FormGroup was mainly useful for adding validators in this case.</p><h3>Summary</h3><p>Overall, my experience with Analog has been a pleasant one. The documentation is well-organized and provides all the necessary information. And if something’s unclear, you can always hop onto their Discord to ask questions or chat with the community.</p><p>But the real question is: would I choose Analog for my next project? Right now, it’s tough to imagine the Angular team coming up with a full-stack solution that could outshine Analog. More and more developers are aware of Analog, so I don’t think it’s going anywhere anytime soon.</p><p>If you’re not working on a fully dashboard-style app (where most of the functionality is behind authentication and you don’t want to set up a separate backend like NestJS), Analog is definitely worth considering. It shines in small to medium-sized projects. For large-scale projects, though? Check with the community on the <a href="https://discord.com/invite/mKC2Ec48U5">Discord channel</a>.</p><p>I hope you enjoyed this article. You can check out the full Anime search example on <a href="https://github.com/krivanek06/analogjs-example-project">GitHub</a>. Feel free to share your thoughts, catch more of my articles on <a href="https://dev.to/krivanek06">dev.to</a>, or connect with me on <a href="https://www.linkedin.com/in/eduard-krivanek">LinkedIn</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-cjK8Q7M394z_Oxz0mlFJg.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efa137a1b59e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/multitude-it-labs/build-a-full-stack-application-with-analogjs-efa137a1b59e">Build A Full-Stack Application With AnalogJS</a> was originally published in <a href="https://medium.com/multitude-it-labs">Multitude IT Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Personal Take On Signal Types In Angular]]></title>
            <link>https://medium.com/multitude-it-labs/my-personal-take-on-signal-types-in-angular-b159bb38211b?source=rss----5c76af6b2fa7---4</link>
            <guid isPermaLink="false">https://medium.com/p/b159bb38211b</guid>
            <dc:creator><![CDATA[Eduard Krivanek]]></dc:creator>
            <pubDate>Wed, 26 Mar 2025 09:49:48 GMT</pubDate>
            <atom:updated>2025-03-28T08:22:02.871Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_JOQFoJV2Mg24ya-yWLBSQ.png" /></figure><p>On May 3, 2023, signals were introduced in Angular v16 as a reactive variable for managing application state. While it was a new feature at the time, by Angular v19.2, signals have already become a well-established API. Although not all legacy corporate projects have adopted signals, most developers are aware of them (whether in a positive light or not).</p><p>In the latest (currently v19.2) we have signal APIs such as httpResource, rxResource / resource &amp;linkedSignal. In this article I want to give my thoughts on signals, how I look at signals, in which situation I use them, and how they compare to alternative approaches, such as RxJS solving the same problem. Blog was originally published on <a href="https://www.angularspace.com/my-personal-take-on-signal-types-in-angular/">Angular-Spaces</a>.</p><h3>Signal Primitives</h3><p><a href="https://angular.dev/guide/signals">Reading Angular’s documentation</a>, they describe that signal() is a wrapper around any primitives or complex data structure that notifies consumers when the value changes.</p><p>I use signal() whenever a variable is used in the DOM and its value updates over time. A common example is toggling between components using two buttons to control which component is displayed.</p><pre>@Component({<br>  selector: &#39;app-test&#39;,<br>  template: `<br>      &lt;button (click)=&quot;onViewChange(&#39;card&#39;)&quot; type=&quot;button&quot;&gt;<br>        Card View<br>      &lt;/button&gt;<br>      &lt;button (click)=&quot;onViewChange(&#39;grid&#39;)&quot; type=&quot;button&quot;&gt;<br>        Grid View<br>      &lt;/button&gt;<br><br>      @if(viewControl() === &#39;grid&#39;) { &lt;app-grid-view /&gt; }<br>      @else if(viewControl() === &#39;card&#39;) { &lt;app-card-view /&gt; }<br>  `,<br>  changeDetection: ChangeDetectionStrategy.OnPush,<br>  standalone: true,<br>})<br>export class TestComponent {<br>  viewControl = signal&lt;&#39;grid&#39; | &#39;card&#39;&gt;(&#39;grid&#39;);<br><br>  onViewChange(view: &#39;grid&#39; | &#39;card&#39;): void {<br>    this.viewControl.update(() =&gt; view);<br>  }<br>}</pre><p>Is signal() the only viable option for this? Not really. An alternative approach could be to create a child component implementing ControlValueAccessor and manage state using reactive forms in the parent to control which view is displayed.</p><pre>@Component({<br>  selector: &#39;app-test&#39;,<br>  template: `<br>      &lt;app-button-grid-card-view-change [formControl]=&quot;viewControl&quot; /&gt;<br><br>      @if(viewControl.value === &#39;grid&#39;) {  &lt;app-grid-view /&gt; }<br>      @else if(viewControl.value === &#39;card&#39;) { &lt;app-card-view /&gt;}<br>  `,<br>  imports: [ReactiveFormsModule],<br>  changeDetection: ChangeDetectionStrategy.OnPush,<br>  standalone: true,<br>})<br>export class TestComponent {<br>  viewControl = new FormControl&lt;&#39;grid&#39; | &#39;card&#39;&gt;(&#39;grid&#39;);<br>}</pre><p>Creating a separate component for our buttons is a realistic approach, especially when dealing with multiple buttons and more complex logic. Worth mentioning that this example will not work with zoneless apps, because viewControl.value is not reactive. The framework will not know about the change. It might work in apps with zone.js, but only because of the &quot;click&quot; event, which is patched by zone.js.</p><p>Instead of using reactive forms, we can improve this scenario by leveraging the <a href="https://angular.dev/api/core/model">model() signal</a> in the child component. This allows the child to notify the parent about which button was clicked, effectively delegating the responsibility of toggling between card and grid views to the child component. Note that viewModel is a viewModel = model&lt;&#39;grid&#39; | &#39;card&#39;&gt;(&#39;grid&#39;) in the child component.</p><pre>@Component({<br>  selector: &#39;app-test&#39;,<br>  template: `<br>      &lt;app-button-grid-card-view-change [(viewModel)]=&quot;viewControl&quot; /&gt;<br><br>      @if(viewControl() === &#39;grid&#39;) {  &lt;app-grid-view /&gt; }<br>      @else if(viewControl() === &#39;card&#39;) { &lt;app-card-view /&gt;}<br>  `,<br>  changeDetection: ChangeDetectionStrategy.OnPush,<br>  standalone: true,<br>})<br>export class TestComponent {<br>  viewControl = signal&lt;&#39;grid&#39; | &#39;card&#39;&gt;(&#39;grid&#39;);<br>}</pre><p>This is all well and good. We now have at least three (if not more) different ways to solve the same problem, and honestly, the differences between them aren’t that significant. Based on the examples, I’d lean toward the third solution. However, as a big RxJS fanboy, I want to dive deeper into effect, httpResource, rxResource, and linkedSignal, how they simplify code, yet still have (for now) some limitations when it comes to shaping the result value.</p><h3>Opinion On Effect</h3><p>When effect() was introduced alongside Angular signals, it&#39;s safe to say we all overused it. For a while, one of the most Googled questions was:</p><blockquote><em>How to fix: Writing to signals is not allowed in a computed or an effect by default. Use allowSignalWrites ….</em></blockquote><p>We quickly discovered that creating infinite loops was easier than we’d like to admit. A classic example looks something like this:</p><pre>effect(() =&gt; {<br>  const user = authUser();<br>  this.methodReadsAndUpdatedSignals(a);<br>})</pre><p>Later, we discovered that we could use untracked() inside effect(), essentially wrapping most of our code in it, to prevent infinite loops. What’s interesting is that, despite effect() being part of the Angular signal API, Angular actually discourages its use except in <a href="https://angular.dev/guide/signals#effects">very rare cases</a>.</p><p>When I built <a href="https://ggfinance.io/">ggfinance.io</a> (<em>small promo</em> 😏), a mid-sized application, I found myself using effect() only in the following scenarios:</p><ul><li>DOM — Initializing charts</li><li>DOM — Displaying data in Angular Material tables</li><li>DOM — Creating structural directives that modify the view based on signal (store) changes</li><li>LOG — Logging signal changes</li></ul><pre>@Component({<br>  selector: &#39;app-test&#39;,<br>  standalone: true,<br>  imports: [MatTableModule, MatPaginatorModule, MatSortModule],<br>  template: `<br>    &lt;table mat-table mat-sort [dataSource]=&quot;dataSource&quot;&gt;<br>      &lt;!-- display columns --&gt;<br>    &lt;/table&gt;<br>    &lt;mat-paginator /&gt;<br>  `,<br>})<br>export class TestComponent {<br>  data = input&lt;unknown[]&gt;();<br><br>  paginator = viewChild(MatPaginator);<br>  sort = viewChild(MatSort);<br><br>  displayedColumns = [&#39;col1&#39;, &#39;col2&#39;];<br>  dataSource = new MatTableDataSource&lt;unknown&gt;([]);<br><br>  tableEffect = effect(() =&gt; {<br>    const data = this.data();<br><br>    untracked(() =&gt; {<br>      this.dataSource.data = data;<br>      this.dataSource.paginator = this.paginator() ?? null;<br>      this.dataSource.sort = this.sort() ?? null;<br>      this.dataSource._updateChangeSubscription();<br>    });<br>  });<br>}</pre><p>Although effect is a building block as such, mainly to issue side-effect tasks, run an independent computation when one or more input values change, other alternatives are preferred when creating a new reactive data structure used in the DOM. Upon a later discovery, as I was writing this article, I realized that you solve some of the mentioned problems with computed(), such as rewriting the mat-table data population as such.</p><pre>@Component({<br>  selector: &#39;app-test&#39;,<br>  standalone: true,<br>  imports: [MatTableModule, MatPaginatorModule, MatSortModule],<br>  template: `<br>    &lt;table mat-table mat-sort [dataSource]=&quot;tableData()&quot;&gt;<br>      &lt;!-- display columns --&gt;<br>    &lt;/table&gt;<br>    &lt;mat-paginator /&gt;<br>  `,<br>})<br>export class TestComponent {<br>  data = input&lt;unknown[]&gt;();<br><br>  paginator = viewChild(MatPaginator);<br>  sort = viewChild(MatSort);<br><br>  displayedColumns = [&#39;col1&#39;, &#39;col2&#39;];<br><br>  tableData = computed(() =&gt; {<br>    const data = this.data();<br>    const dataSource = new MatTableDataSource&lt;unknown&gt;([]);<br><br>    dataSource.data = data;<br>    dataSource.paginator = this.paginator() ?? null;<br>    dataSource.sort = this.sort() ?? null;<br><br>    return dataSource<br>  });<br>}</pre><h3>Opinion On linkedSignal</h3><p>While computed() is a signal whose value is derived or computed from one or more other signals (dependencies), it is inherently a readonly signal. However, there are cases when you need to compute a signal, update its value over time, and then reset it back to its initial state when a dependency changes.</p><p>An example of this might be in an online store, ordering application, or a simple SaaS app. Imagine you have a scenario where a user selects an item. The initial quantity will always be 1, but the user can increment the quantity. However, when a new item is selected, the quantity should reset to 1. Below are two examples of how to achieve this behaviour, both before and after the introduction of linkedSignal().</p><pre> // EXAMPLE BEFORE linkedSignal()<br> itemSelected = signal&lt;unknown&gt;(null);<br> itemUnits = signal(1);<br><br> // everytime a new item is selected, reset units to 0<br> itemUnitsEffect = effect(() =&gt; {<br>   const selected = this.itemSelected();<br><br>   untracked(() =&gt; {<br>     this.itemUnits.set(1);<br>   })<br> })</pre><pre>// EXAMPLE USING linkedSignal()<br>itemSelected = signal&lt;unknown&gt;(null);<br><br>itemUnits = linkedSignal({<br>    source: this.itemSelected,<br>    computation: () =&gt; 1<br>});</pre><p>I think linkedSignal() particularly useful in cases where:</p><ul><li>State reset on dependency change, like in the example of selecting a product on an e-commerce site and resetting quantities back to the default value when a new item is selected.</li><li>Conditional state, when you want to link one signal’s state to another and have the ability to reset or adjust its value based on the context of the other signal.</li><li>Complex UI interactions, such as wizards or multi-step forms, where one step’s state depends on another, and you need to preserve or reset values depending on the flow.</li></ul><p>That said, linkedSignal() might not be necessary for every use case. It’s useful for scenarios where you need more than just a computed signal but don’t want to deal with the complexity of manually resetting or synchronizing state.</p><h3>Opinion On httpResource &amp; rxResource/resource</h3><p>The recent Angular versions introduced two useful signal APIs designed to work with async data:</p><ul><li>httpResource – <a href="https://github.com/angular/angular/pull/59876">available in version 19.2</a></li><li>rxResource/resource – <a href="https://github.com/angular/angular/pull/58255">available in version 19.0</a></li></ul><p>Initially, I had mixed feelings about these two functions because, since we can achieve very similar behaviour using RxJS. However, I realized that the long-term goal of the Angular team seems to be reducing the reliance on RxJS. Looking at httpResource, its description says:</p><blockquote><em>Uses HttpClient to make requests and supports interceptors, testing, and other features of the HttpClient API. Data is parsed as JSON by default.</em></blockquote><pre>data1 = toSignal(this.http.get&lt;unknown&gt;(&#39;...&#39;).pipe(map((d) =&gt; d.data)<br> ), { initialValue: [] });<br><br> data2 = httpResource&lt;unknown[]&gt;(<br>    () =&gt; ({<br>      method: &#39;GET&#39;,<br>      url: &#39;&#39;,<br>  }), { defaultValue: [], parse: (d): unknown[] =&gt; d.data });</pre><p>At first, I thought the two approaches were almost identical. However, I quickly realized I was mistaken. The httpResource API provides additional built-in states like isLoading and error, which are incredibly useful for tracking the request’s status.</p><p>Furthermore, because httpResource is a WritableResource, it allows not just to observe state changes but also directly manipulate that state, manually setting the state of the signal, such as data2.set([]). This contrasts with the traditional toSignal API, which is a read-only signal.</p><p>Additionally, httpResource gives us the progress of the HTTP request, and we can use reload() to trigger the HTTP request again.</p><p>Let’s look at the following example. We have a search bar that loads items based on the prefix and selected genres, and when an item is selected, the search results will be dismissed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mFe6hAUURAglrlZnRf3y8Q.png" /><figcaption>Overview Of A Simple Search</figcaption></figure><p>To achieve this behaviour with the new signal APIs, we could implement something like the code below. I’d say the code is definitely easy to read and doesn’t require RxJS.</p><p>As you type into the input, the values are saved in the searchControl signal. When the genre is changed, it gets saved in the selectedGenresId signal. I haven’t included the HTML part since I believe it&#39;s not crucial for this example.</p><pre>export class SearchComponent {<br>  private apiService = inject(AnimeApiService);<br><br>  selectedData = output&lt;AnimeData&gt;();<br><br>  // control signal to select a genre and item prefix<br>  searchControl = signal(&#39;&#39;);<br>  selectedGenresId = signal&lt;number&gt;(1);<br><br>  // load options if genre or prefix changes<br>  searchedDataResource = rxResource({<br>    request: () =&gt; ({<br>      genresId: this.selectedGenresId(),<br>      prefix: this.searchControl(),<br>    }),<br>    loader: ({ request }) =&gt;<br>      this.apiService.searchAnime(request.prefix, request.genresId),<br>        defaultValue: [],<br>  });<br><br>  onGenresClick(id: number): void {<br>    this.selectedGenresId.set(id);<br>  }<br><br>  onClick(animeData: AnimeData): void {<br>    // emit to parent<br>    this.selectedData.emit(animeData)<br>    // reset displayed data<br>    this.searchedDataResource.value.set([]);<br>  }<br>}</pre><p>One small thing I’d like to highlight with this approach is the difference between <a href="https://dev.to/krivanek06/from-chaos-to-clarity-simplify-your-angular-code-with-declarative-programming-58gm">declarative and imperative programming</a>.</p><p>In the searchedDataResource, we have the loaded items. However, when an item is selected, we imperatively change searchedDataResource to an empty array, somewhere in the program, to hide the loaded results.</p><p>The question I want to explore is: What would be the RxJS equivalent of this code, where we want to keep track of both the loading and error states of network requests?</p><pre>export class SearchComponent {<br>  private apiService = inject(AnimeApiService);<br><br>  // control for item prefix<br>  searchControl = new FormControl&lt;string&gt;(&#39;&#39;, {<br>    nonNullable: true,<br>  });<br><br>  // control to select a genre<br>  selectedGenresIdControl = new FormControl&lt;number&gt;(1, {<br>    nonNullable: true,<br>  });<br><br>  selectedData$ = new Subject&lt;AnimeData&gt;();<br><br>  // notifies parent when item is selected<br>  selectedAnime = outputFromObservable(this.selectedAnime$);<br><br>  searchedData = toSignal(<br>    this.selectedGenresIdControl.valueChanges.pipe(<br>      switchMap((genderId) =&gt;<br>        this.searchControl.valueChanges.pipe(<br>          // search immediatelly with new genres<br>          startWith(this.searchControl.value),<br>          // load from API<br>          switchMap((name) =&gt;<br>            this.apiService.searchAnime(name, genderId).pipe(<br>              map((data) =&gt; ({ data, isLoading: false })),<br>              startWith({ data: [], isLoading: true }),<br>              catchError((e) =&gt; <br>                  of({ data: [], error: e, isLoading: false })<br>                ),<br>            ),<br>          ),<br>          // listen on select and reset the data<br>          switchMap((result) =&gt;<br>            this.selectedData$.pipe(<br>              map(() =&gt; ({ data: [], isLoading: false })),<br>              startWith(result),<br>            ),<br>          ),<br>        ),<br>      ),<br>    ),<br>    { initialValue: { data: [] as AnimeData[], isLoading: false } },<br>  );<br><br>  onClick(data: AnimeData): void {<br>    this.selectedData$.next(data);<br>  }<br>}</pre><p>One might argue that the rxResource version is shorter, more readable, therefore a better choice. While readability certainly wins here, what I personally miss from signals are the utility functions that RxJS provides, such as distinctUntilChanged(), debounceTime(), and others for manipulating data.</p><p>To further reduce the complexity in RxJS, which typically handles the loading and error states of network requests, you can abstract the logic by <a href="https://dev.to/this-is-angular/create-custom-rxjs-operators-edd">creating custom RxJS operators</a>.</p><p>If you want to minimize RxJS usage, but still need functionality like debouncing, you could either use <a href="https://lodash.com/docs/4.17.15">Lodash</a> or combine RxJS with rxResource to achieve something like this:</p><pre>export class AnimeSearchNewComponent {<br>  private readonly apiService = inject(AnimeApiService);<br><br>  // control signal to select a genre and item prefix<br>  readonly searchControl = signal(&#39;&#39;);<br>  readonly searchControlSignal = toSignal(<br>    toObservable(this.searchControl).pipe(<br>      distinctUntilChanged(),<br>      debounceTime(300),<br>    )<br>  )<br><br>  // load options if genre or prefix changes<br>  readonly searchedDataResource = rxResource({<br>    request: () =&gt; ({<br>      prefix: this.searchControlUsed(),<br>    }),<br>    loader: ({ request }) =&gt;<br>      this.apiService.searchAnime(request.prefix),<br>        defaultValue: [],<br>  });<br>  }</pre><p>One thing to consider with signals is that while they provide a simpler API for managing state, RxJS still has its place for more complex scenarios where you need to do heavy data transformation or work with <a href="https://dev.to/krivanek06/angular-interview-what-is-higher-order-observable-2k03">higher-order observables</a>. Signals shine in cases where you just need to track a value and its changes, whereas RxJS excels when you’re dealing with multiple asynchronous streams, operators like combineLatest or switchMap, and complex transformations.</p><h3>Summary</h3><p>No one can argue that Angular’s team doesn’t deliver new and useful features. Perhaps it’s because I’ve been part of the ecosystem for so long, or because of my experience with RxJS, that I feel the need to discuss this topic. It’s also worth mentioning the new RFCs about resource architecture:</p><ul><li><a href="https://github.com/angular/angular/discussions/60120">Resource RFC 1: Architecture</a></li><li><a href="https://github.com/angular/angular/discussions/60121">Resource RFC 2: APIs</a></li></ul><p>The ongoing RFCs about the resource architecture will likely shape the direction Angular takes with handling asynchronous data.</p><p>When I first set out to write this article, I didn’t quite understand the usefulness of rxResource and httpResource, thinking that you could achieve the same or similar results with signals. However, after creating a small example of the search box – <a href="https://github.com/krivanek06/stackblitz-signal-example">available on GitHub</a> – I came to appreciate that having more options to accomplish the same result is actually a good thing. Whether you choose RxJS or signals depends on your preferences and the needs of your project as both have their place in Angular development.</p><p>Finally I do recommend taking a look on <a href="https://www.youtube.com/watch?v=GXzPlaF3-bE">HttpResource in Angular 19.2 from Decoded Frontend</a> as he explains lots of functionalities with the HttpResource. I hope you enjoyed my musings on this topic. You can also read more from me on <a href="https://dev.to/krivanek06">dev.to</a> or connect with me on <a href="https://www.linkedin.com/in/eduard-krivanek">LinkedIn</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Gqs5xCMOUT2mnCubJuQjjA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b159bb38211b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/multitude-it-labs/my-personal-take-on-signal-types-in-angular-b159bb38211b">My Personal Take On Signal Types In Angular</a> was originally published in <a href="https://medium.com/multitude-it-labs">Multitude IT Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Custom RxJs Operators]]></title>
            <link>https://medium.com/multitude-it-labs/creating-custom-rxjs-operators-34354f80fd93?source=rss----5c76af6b2fa7---4</link>
            <guid isPermaLink="false">https://medium.com/p/34354f80fd93</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[webdev]]></category>
            <dc:creator><![CDATA[Eduard Krivanek]]></dc:creator>
            <pubDate>Wed, 19 Feb 2025 08:16:19 GMT</pubDate>
            <atom:updated>2025-03-28T08:23:14.904Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9pOjS12EB0vJl8XV782P8Q.png" /></figure><p>This article was originally posted on <a href="https://www.angularspace.com/create-custom-rxjs-operators/">Angular Spaces</a>. On the recent Angular live interview in January 2025 a question was asked: “<a href="https://www.youtube.com/live/apyVs0D6rf0?t=3228s">Are we ditching Observables and RxJs?</a>”.<br>A simple answer is that RxJs had became optional, but it is far from obsolete. The introduction of signals has added a new tool to Angular’s reactive programming toolbox, but RxJs remains valuable for scenarios involving complex data streams, event handling, and real-time updates.</p><p>I’ve already written two articles in 2024 on Advanced RxJs Operators You Know But Not Well Enough — <a href="https://dev.to/krivanek06/advanced-rxjs-operators-you-know-but-not-well-enough-1ela">part 1</a> and <a href="https://dev.to/this-is-angular/advanced-rxjs-operators-you-know-but-not-well-enough-pt-2-3df5">part 2</a>, which received positive feedback.<br>Even though there are plenty of operators to choose from the official RxJs docs, there are times when you wish for a particular operator to solve a unique use case.</p><p>In this article, I want to explore how you can create custom RxJs operators and then give you some operators (not just simple loggers) that may be useful to your application. Every operator that will be mentioned in the article can be found in the <a href="https://github.com/krivanek06/stackblitz-rxjs-playground/tree/main/src/custom-rxjs-operators">Github Repository</a>. Those customs operators include:</p><ul><li>filterNil() - filters out null and undefined values from the pipe chain</li><li>dataPolling() - poll data from an API in some time interval</li><li>handleError() - complex error handling by sending data to Sentry and notifying the user</li><li>rememberHistory() - caching last N values and accessing previous state of the received data</li><li>objectValueChanged() - deep object comparison, emitting only changed states compared to previous</li><li>objectChangedFields() - listing out an object’s (form) changed fields</li><li>loadingStatus() - similar to the rxResource() API, that works with Observables</li></ul><h3>What Is An Operator?</h3><p>To answer this question, it’s best to start by looking at the <a href="https://github.com/ReactiveX/rxjs/tree/master/packages/rxjs/src/internal/operators">Github RxJs implementations</a> for all available operators. Let’s choose the most common map() operator and see how it is being implemented. At the moment of writing this article, in RxJs version 7.8.1, the map() operator implementation looks as follows:</p><pre>export function operate&lt;In, Out&gt;(<br>    { destination, ...subscriberOverrides }: OperateConfig&lt;In, Out&gt;<br>) {<br>  return new Subscriber(destination, subscriberOverrides);<br>}<br><br>export function map&lt;T, R&gt;(<br>    project: (value: T, index: number) =&gt; R<br>): OperatorFunction&lt;T, R&gt; {<br>  return (source) =&gt;<br>    new Observable((destination) =&gt; {<br>      // The index of the value from the source.<br>      let index = 0;<br>      // Subscribe to the source<br>      source.subscribe(<br>        operate({<br>          destination,<br>          next: (value: T) =&gt; {<br>            // Call the projection function with the context,<br>            // and send the resulting value to the consumer.<br>            destination.next(project(value, index++));<br>          },<br>        })<br>      );<br>    });<br>}</pre><p>This is nice and all, but what does this piece of code tell us? My main takeaway is that, the map() operator is simple a JavaScript function that returns a specific OperatorFunction&lt;T, R&gt; type. The logic what exactly happens inside the function is now irrelevant. What I want to focus on is the returning type. Reading the <a href="https://github.com/ReactiveX/rxjs/blob/master/packages/observable/src/types.ts#L29">return type explanation on Github</a>, the authors explain that there are actually two operator types: OperatorFunction and MonoTypeOperatorFunction.</p><p>The OperatorFunction type &quot;<em>always takes a single parameter (the source Observable) and returns another Observable.</em>”. The reason why this type is used with the map() operator is that it takes some sort of generic value T as an input and returns a different output R value. This actually makes sense as we can write a predicate that transforms the entire shape of the input object T -&gt; R.</p><p>When the output type is the same type as the input type, we can use the MonoTypeOperatorFunction. It’s description says “<em>A function type interface that describes a function that accepts and returns a parameter of the same type.</em>”.</p><p>Also worth pointing out that the source variable represents the Observable passed into the operator function when it is invoked within a pipe chain. Meaning when you use the source.subscribe(value =&gt; ... ) then value represents the data flowing through the pipe chain into this function.</p><h3>Start With Basics</h3><p>End of the theory, let’s dive into something practical to understand the basics. To create a simple custom operator, let’s say that we have a stream of numbers and want to multiply them by a specific value. Here’s the result we aim to achieve:</p><pre>const source$ = of(1, 2, 3);<br>source$.pipe(multiplyBy(6)).subscribe(console.log);<br>//  6, 12, 18</pre><p>From what we know so far, we can create something like this:</p><pre>export function multiplyBy(val = 2): MonoTypeOperatorFunction&lt;number&gt; {<br>  return (source: Observable&lt;number&gt;): Observable&lt;number&gt; =&gt;<br>    new Observable&lt;number&gt;((subscriber) =&gt; {<br>      return source.pipe(map((d) =&gt; d * val)).subscribe({<br>        next(value) {<br>          subscriber.next(value);<br>        },<br>        error(err) {<br>          subscriber.error(err);<br>        },<br>        complete() {<br>          subscriber.complete();<br>        },<br>      });<br>    });<br>}</pre><p>The function name is multiplyBy() which is used inside a pipe chain. It returns a MonoTypeOperatorFunction type because, although we modify the data, the type remains the same. Inside the function, we subscribe to the current Observable to access the values flowing through the pipe chain and return a new Observable.</p><p>This implementation works fine, however, I didn’t like this extra layer of abstraction by creating an additional Observable wrapping around the source Observable, and also explicitly subscribing to the source. This approach is useful if we need full control over subscription management or have complex custom logic. Since none of these apply to our code, we can simplify our custom operator as follows:</p><pre>export function multiplyBy(val = 2): MonoTypeOperatorFunction&lt;number&gt; {<br>  return (source) =&gt; source.pipe(map((d) =&gt; d * val));<br>}</pre><p>The shorter syntax is more readable, so I will continue with it to list out some operators that may be useful in your projects, starting from simple ones up to more complicated ones.</p><h3>Custom RxJs Operators</h3><h3>1.) Filter Nil</h3><p>The inspiration for this operator came from the <a href="https://ngxtension.netlify.app/utilities/operators/filter-nil/">ngxtension</a> library, that I used for some time and I do recommend checking it out. The idea is that we want to filter out undefined and null values from a pipe chain.</p><pre>export function filterNil&lt;T&gt;(): MonoTypeOperatorFunction&lt;T&gt; {<br>  return (source) =&gt; source.pipe(<br>      filter((d) =&gt; d !== null &amp;&amp; d !== undefined)<br>     );<br>}</pre><h3>2.) Data Polling</h3><p>There are situations where you loaded data from an API, cached it, but you wanted to poll the server in some time interval, thought the lifetime of the application, to refresh the data — weather app, stock prices, message polling etc. What I found out was, that it was pretty easy to implement such an operator:</p><pre>export function dataPolling&lt;T&gt;(data: {<br>  loader: () =&gt; Observable&lt;T&gt;;<br>  reloadSeconds: number;<br>}): MonoTypeOperatorFunction&lt;T&gt; {<br>  return (source) =&gt;<br>    source.pipe(<br>      switchMap(() =&gt;<br>        timer(0, data.reloadSeconds * 1000).pipe(<br>          switchMap(data.loader)<br>        )<br>      )<br>    );<br>}</pre><pre>// Component<br>private http = inject(HttpClient);<br><br>constructor() {<br>  const api = &#39;...&#39;<br>  this.http.get(api)<br>    .pipe(<br>      dataPolling({<br>         reloadSeconds: 10,<br>         loader: () =&gt; this.http.get(api),<br>      }),<br>    ).subscribe((x) =&gt; console.log(x));<br>}</pre><h3>3.) Complex Error Handling</h3><p>I know I said I won’t do examples with logging, as you can find more than enough of it, however I think it is worth mentioning that when you are doing some more complex logic inside the catchError() operator, it makes sense to create a custom operator for it. Here is an example of reporting the logs into Sentry and also notifying the user when something goes wrong.</p><pre>export function handleError&lt;T, K&gt;(<br>  returnValue: K,<br>  errorMessage = &quot;Server Error&quot;<br>): OperatorFunction&lt;T, K | T&gt; {<br>    const sentry = inject(SentryService);<br>    const notification = inject(NotificationService);<br><br>    return (source) =&gt;<br>      source.pipe(<br>        catchError((err) =&gt; {<br>          // log error in sentry<br>          sentry.log(error, &#39;error&#39;)<br>          // notify the user<br>          notification.notifyUser(errorMessage, &#39;error&#39;)<br>          // return something in the pipe chain<br>          return of(returnValue);<br>        })<br>     );<br>}</pre><h3>4.) Remember History</h3><p>Have you ever had a situation that you wanted to create an “undo change” button? Maybe caching values that arrived via a Websocket connection, or remember last N form edits by the user? One simple version for caching data can be done as follows:</p><pre>// defining an interface for the function<br>// current and crevious values can be different, therefore T &amp; K<br>type RememberMemory&lt;T, K = T&gt; = {<br>    // previous value that was cachced<br>  previous: null | K;<br>  // currently cached value<br>  current: T;<br>  // previous N cached values<br>  historyChain: unknown[];<br>};</pre><pre>export function rememberHistory&lt;T&gt;(<br>    // how many last N values to remember<br>  memory = 3<br>): OperatorFunction&lt;T, RememberMemory&lt;T&gt;&gt; {<br>  return (source) =&gt;<br>    source.pipe(<br>      scan(<br>        (acc, curr) =&gt; ({<br>          current: curr,<br>          previous: acc.current,<br>            // remember last N values<br>          historyChain: [...acc.historyChain.slice(-(memory - 1)), curr]<br>        }),<br>        {<br>          current: null as T, // ignore initial null<br>          previous: null,<br>          historyChain: [],<br>        } as RememberMemory&lt;T&gt;<br>      )<br>    );<br>}</pre><p>To demonstrate how this pipe works, let’s say you have a stream of data and you want to cache them. When you have the following code, it will result to the below displayed picture. You can also change the logic if you want to change the order in the historyChain to keep the latest data on the first and not on the last position in the array.</p><pre>from([<br>  { id: 1, name: &quot;test1&quot; },<br>  { id: 2, name: &quot;test2&quot; },<br>  { id: 3, name: &quot;test3&quot; },<br>  { id: 4, name: &quot;test4&quot; },<br>]).pipe(<br>    rememberHistory(4)<br>  )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*2_NY_kyXvEwRQCa6bKQYoQ.png" /><figcaption>Custom Pipe Remember History Log</figcaption></figure><h3>5.) Object Value Change</h3><p>When working with forms, you might listen to the form’s valueChanges and only perform specific computations when the form is actually updated. The goal is to ignore intermediate changes, like typing or deleting characters, and only respond to meaningful updates. To solve this you could reach out for distinctUntilChanged() with some predicate and write it as:</p><pre>this.myForm.valueChanges.pipe(<br>  debounceTime(800),<br>  distinctUntilChanged(<br>    (prev, curr) =&gt; JSON.stringify(prev) === JSON.stringify(curr)<br>  ),<br>  map(d =&gt; /* do something */ )<br> )</pre><p>Using the stringifycation predicate, you are creating a guard to proceed only when the form was updated from it’s previous state. This predicate performs a deep comparison, which also includes checking form arrays and nested form groups.</p><p>But what if you need this logic, but you wish to avoid using JSON.stringify ? You’d want a way to compare the previous and current object states, emitting only when they differ. Restricting the usage of distinctUntilChanged() and write out a custom logic to compare object changes can be done as follows:</p><pre>/**<br> * creates a deep comparison between previous and current state<br> * and emits only when object values changed (even for nested keys)<br> */<br>export function objectValueChanged&lt;T extends Object&gt;(<br>  config: {<br>    debounceTime: number;<br>  } = {<br>    debounceTime: 500,<br>  }<br>): MonoTypeOperatorFunction&lt;Partial&lt;T&gt;&gt; {<br>  const isObjectValueChange = &lt;K extends Object | {}&gt;(<br>    prev: K,<br>    curr: K<br>  ): boolean =&gt; {<br>    return Object.keys(curr).some((key) =&gt; {<br>      // value can be anything - string, number, object, etc.<br>      const previousValue = prev[key as keyof K] as any;<br>      const currentValue = curr[key as keyof K] as any;<br><br>      // if value is object - check child key and value changes<br>      if (currentValue instanceof Object) {<br>        return isObjectValueChange(previousValue, currentValue);<br>      }<br>      return previousValue !== currentValue;<br>    });<br>  };<br>  return (source) =&gt;<br>    source.pipe(<br>      // start with empty object make first emit<br>      startWith({}),<br>      // wait for user&#39;s input typing<br>      debounceTime(config.debounceTime),<br>      // use previous and current object values<br>      pairwise(),<br>      // only filter changed values for the object<br>      filter(([prev, curr]) =&gt; isObjectValueChange(prev, curr)),<br>      // return current object<br>      map(([_, curr]) =&gt; curr)<br>    );<br>}</pre><h3>6.) Object Field Changes</h3><p>Speaking about forms, a more practical use case could be listening to a form and determining which fields have been changed / edited. The goal is to pass the initial state of the form (or object) into the pipe and get two outputs: an array of changed keys and an object where the keys are form field names and the values are booleans indicating if the field was edited. This pipe is indeed more complex, you don’t need to understand it in depth. Below I demonstrate how it works when attaching it on a form.</p><pre>type Booleanify&lt;T&gt; = {<br>  [K in keyof T]: T[K] extends object ? Booleanify&lt;T[K]&gt; : boolean;<br>};<br><br>export function objectChangedFields&lt;T extends Object&gt;(<br>  initial: T<br>): OperatorFunction&lt;<br>  Partial&lt;T&gt;,<br>  {<br>    viewArray: string[];<br>    viewObject: Booleanify&lt;T&gt;;<br>  }<br>&gt; {<br>  // identify which fields have changed between two states.<br>  const getChangedFields = &lt;K extends Object | Array&lt;any&gt;&gt;(<br>    initial: K,<br>    current: Partial&lt;K&gt;,<br>    currentKey = &quot;&quot;<br>  ): string[] =&gt; {<br>    let changedKeys: string[] = [];<br>    for (const key of Object.keys(current)) {<br>      // value can be anything - string, number, object, etc.<br>      const previousValue = initial[key as keyof K] as any;<br>      const currentValue = current[key as keyof K] as any;<br><br>      // create key to save<br>      const newKey = currentKey !== &quot;&quot; ? `${currentKey}.${key}` : key;<br><br>      // if value is object - check child key and value changes<br>      if (currentValue instanceof Object) {<br>        // save nested path<br>        changedKeys.push(<br>          ...getChangedFields(previousValue, currentValue, newKey)<br>        );<br>        // go to next key<br>        continue;<br>      }<br><br>      // string or number comparison<br>      if (previousValue !== currentValue) {<br>        changedKeys.push(newKey);<br>      }<br>    }<br><br>    // return saved keys<br>    return changedKeys;<br>  };<br><br>  // identify which fields have changed between two states.<br>  const getChangedFieldsObject = &lt;K extends Object&gt;(<br>    initial: Partial&lt;K&gt;,<br>    current: Partial&lt;K&gt;,<br>    cachedObj = {}<br>  ): Booleanify&lt;K&gt; =&gt; {<br>    for (const key of Object.keys(initial)) {<br>      // value can be anything - string, number, object, etc.<br>      const previousValue = initial[key as keyof K] as any;<br>      const currentValue = current[key as keyof K] as any;<br><br>      // if value is object - check child key and value changes<br>      if (currentValue instanceof Object) {<br>        // create nested object<br>        (cachedObj as any)[key] = {};<br>        // access nested cache<br>        const nestedCache = (cachedObj as any)[key];<br>        // check if nested key changed<br>        getChangedFieldsObject(previousValue, currentValue, nestedCache)<br>        // go to next key<br>        continue;<br>      }<br><br>      // string or number comparison<br>      (cachedObj as any)[key] = previousValue !== currentValue;<br>    }<br><br>    return cachedObj as Booleanify&lt;K&gt;;<br>  };<br><br>  return (source) =&gt;<br>    source.pipe(<br>      map((data) =&gt; ({<br>        viewArray: getChangedFields(initial, data),<br>        viewObject: getChangedFieldsObject(initial, data),<br>      }))<br>    );<br>}</pre><p>I won’t dive into the details of how it works, there are some any castings and probably if you spend enough time on this, you could make it cleaner, but I’ve linked the GitHub repository at the end for those interested.</p><p>What’s important is that you pass the initial state of the object (form) as initial: T to the function. The two functions, getChangedFields() returns an array of keys which were affected, and getChangedFieldsObject() returns an object with boolean values if the key was. changed. Now, let’s see this pipe in action with the following component:</p><pre>export class ExampleFormComponent {<br>  private readonly builder = inject(FormBuilder);<br><br>  myForm = this.builder.nonNullable.group({<br>    name: [&quot;&quot;],<br>    email: [&quot;&quot;],<br>    age: [&quot;&quot;],<br>    address: this.builder.group({<br>      city: [&quot;&quot;],<br>    }),<br>    items: this.builder.array([<br>      this.builder.group({<br>        name: [&quot;&quot;],<br>        amount: [0],<br>      }),<br>    ]),<br>  });<br><br>  constructor() {<br>    this.myForm.valueChanges.pipe(<br>        objectChangedFields(this.myForm.value)<br>      ).subscribe((fieldChange) =&gt; {<br>        console.log(&quot;Changed fieldsa:&quot;, fieldChange);<br>      });<br>  }<br>}</pre><p>I am passing the this.myForm.value initial state to the custom pipe, but this can be any object to which I want to compare the pipe chain data into. For instance, if the name, address.city and items[0].name fields will be changed, the objectChangedFields() will return the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*dSJYIuIp8qLSQfUZH5z72g.png" /><figcaption>Custom Pipe Object Changed Fields Log</figcaption></figure><h3>7.) Loading Stats</h3><p>In November 2024 I published an article titled <a href="https://dev.to/this-is-angular/creating-custom-rxresource-api-with-observables-2abm">Creating Custom rxResource API With Observables</a>, where I attempted to recreate a custom rxResource() API that works with Observables instead of signals. The main benefit of this custom API is that, even when working with Observables, you still get access to the loading state of the HTTP request. What I also realized is that I can take this logic and create a custom pipe that includes these HTTP status indicators.</p><pre>type RxResourceResult&lt;T&gt; = {<br>  state: &quot;loading&quot; | &quot;loaded&quot; | &quot;error&quot;;<br>  isLoading: boolean;<br>  data: T | null;<br>  error?: unknown;<br>};</pre><pre>/**<br> * used mainly for API requests to include HTTP state &amp; data<br> * about the HTTP call. Similar to rxResource<br> */<br> export function loadingStatus&lt;T&gt;(): <br>     OperatorFunction&lt;T, RxResourceResult&lt;T&gt;&gt; <br> {<br>  return (source) =&gt;<br>    source.pipe(<br>      map((result) =&gt; ({<br>        state: &quot;loaded&quot; as const,<br>        data: result,<br>      })),<br>      // setup loading state<br>      startWith({<br>        state: &quot;loading&quot; as const,<br>        data: null,<br>      }),<br>      // handle error state<br>      catchError((error) =&gt;<br>        of({<br>          state: &quot;error&quot; as const,<br>          error,<br>          data: null,<br>        })<br>      ),<br>      // map the result to the expected type<br>      map(<br>        (result) =&gt;<br>          ({<br>            ...result,<br>            isLoading: result.state === &quot;loading&quot;,<br>          } satisfies RxResourceResult&lt;T&gt;)<br>      )<br>    );<br> }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*ebBIS3TtGnN_XdPXPqHy6g.png" /><figcaption>Custom Pipe Loading State Log</figcaption></figure><h3>Summary</h3><p>RxJs already provides bunch of operators to manipulate data in the pipe chain, however, occasionally it happens that you need to create a custom, more specific pipe. From this article, you learned that operators are just simple functions that return either OperatorFunction when the input and output types are different, or MonoTypeOperatorFunction when they stay the same type.</p><p>You also have seen a few examples where custom operators could be useful. Personally, I find the objectChangedFields() and loadingStatus() operators to be the most useful. I hope you liked the article. You can find all the above mentioned, and more custom pipe on the following <a href="https://github.com/krivanek06/stackblitz-rxjs-playground/tree/main/src/custom-rxjs-operators">Github repository</a>. Feel free to share your thoughts, and connect with me on <a href="https://dev.to/krivanek06">dev.to</a> | <a href="https://www.linkedin.com/in/eduard-krivanek">LinkedIn</a> .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*s1cg-4-0m6cc4NAxO9MZ6Q.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34354f80fd93" width="1" height="1" alt=""><hr><p><a href="https://medium.com/multitude-it-labs/creating-custom-rxjs-operators-34354f80fd93">Creating Custom RxJs Operators</a> was originally published in <a href="https://medium.com/multitude-it-labs">Multitude IT Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Story Behind Fetching An API or JSON]]></title>
            <link>https://medium.com/multitude-it-labs/ever-wondered-what-really-happens-when-you-fetch-json-06e3b58b4df8?source=rss----5c76af6b2fa7---4</link>
            <guid isPermaLink="false">https://medium.com/p/06e3b58b4df8</guid>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[fetch-api]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[promises]]></category>
            <dc:creator><![CDATA[Marek Panti]]></dc:creator>
            <pubDate>Wed, 19 Feb 2025 08:15:58 GMT</pubDate>
            <atom:updated>2025-03-28T08:33:58.834Z</atom:updated>
            <content:encoded><![CDATA[<p>How do you properly fetch JSON in JavaScript? And how does an HTTP request work? These are topics that we, as front-end developers, use every day. However, when we look deeper, we often don’t fully understand the underlying engine — how it really works under the hood.</p><blockquote>Let’s grab a coffee and look at the basic fetch operation in JavaScript. Then, we will analyze it further.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZTph-VrGCHAn-OnUFgixow.png" /></figure><pre>const dummyJSONUrl = &#39;https://dummyjson.com/products&#39;;<br><br>async function fetchAPI(url) {<br>const response = await fetch(url, {<br>  method: &#39;GET&#39;,<br>  headers: {<br>    &#39;Content-Type&#39;: &#39;application/json&#39;<br>  }, <br>})<br>    return await response.json();<br>}<br><br>await fetchAPI(dummyJSONUrl);</pre><h4>Async Await Explained</h4><p>async/await is not only a cleaner way of writing promises, but it also prevents blocking the stack. (I am planning an article that will explain the event loop and the call stack.) It helps you organize code better and avoid &quot;callback hell.&quot;</p><p>A function declared with async always returns a promise. The await keyword pauses execution until the promise resolves and returns its result.</p><p>Additionally, fetch is a JavaScript method responsible for making server calls. It supports various HTTP methods, including GET, POST, PUT, DELETE, and PATCH. It allows specifying the request URL, headers, and body (if needed). Of course, you can add error handling to manage server responses and errors using try...catch.</p><h4>Callback Hell Example</h4><p>You can still use a classic promise with .then() resolution. Sometimes, having a single callback function is convenient. However, in the past, when this was the only option, handling multiple requests and mapping responses often led to the so-called &quot;callback hell.&quot;</p><pre>// callback hell example<br>setTimeout(() =&gt; {<br>  console.log(&#39;I am lazy&#39;);<br>  return setTimeout(() =&gt; {<br>    console.log(&#39;I am still lazy&#39;);<br>    return setTimeout(() =&gt; {<br>          return &#39;Start work!&#39;; <br>    }, 100);<br>  }, 100);<br>}, 100);</pre><h3>But What Is The Whole Lifecycle Behind?</h3><blockquote>When you type a URL into your browser and hit Enter, or when an application makes an API call, this is the process getting kickstarted. If the request is HTTPS, additional steps to secure the request are also initialized.</blockquote><p>First, the client must prepare the request. The request is prepared with the query params, the body and header — with some additional information such as Authorization token.</p><p>Then the ssl/tls handshake is in place where the server with the client exchanges the cryptographic information, it happens in case there is a <strong>https</strong> connection. Otherwise the process is a bit simpler: our client sends a request to the server we want to connect to. Now if we have a valid request, our server sends back the SYN+ACK request back to our client. The SYN part is important, because of the server-client connection.</p><p>Now our local system will make a call to the domain name service, to obtain an IP address.</p><h3>DNS Resolution and Internet Service Provider Request</h3><p>A process of identification of IP addresses of every party involved from your local machine, router, internet provider, server etc…</p><p>This topic is so complex, that I won&#39;t write even the basics of the process, if you want to know more I recommend to watch this video: <a href="https://www.youtube.com/watch?v=TTH_f2lKHRM">https://www.youtube.com/watch?v=TTH_f2lKHRM</a></p><h3>Firewall and Nodes</h3><p>After the dns process there is still a firewall barrier on the server, that checks the incoming requests and handles it accordingly.</p><p>Then the request goes to various caching systems and load balancer etc.</p><p>I found really great article about the whole process, <a href="https://dev.to/ashevelyov/the-step-by-step-journey-of-a-network-request-1d10">https://dev.to/ashevelyov/the-step-by-step-journey-of-a-network-request-1d10</a></p><blockquote>Why is it important to understand the process? Imagine that you have a certain bug. Your request fails, and as a front-end developer you go directly to your BE developer and start a discussion. Isn&#39;t it better to understand the whole process, and therefore become a better developer with better debugging skills?</blockquote><h3>Conclusion</h3><p>Understanding how fetch works and what happens under the hood is crucial for debugging network requests efficiently. By learning about async/await, HTTP request lifecycle, and networking fundamentals, you can become a more effective front-end developer.</p><blockquote>What is your biggest challenge with async/await?</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=06e3b58b4df8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/multitude-it-labs/ever-wondered-what-really-happens-when-you-fetch-json-06e3b58b4df8">The Story Behind Fetching An API or JSON</a> was originally published in <a href="https://medium.com/multitude-it-labs">Multitude IT Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Service Instantiation In Angular]]></title>
            <link>https://medium.com/multitude-it-labs/dynamic-service-instantiation-in-angular-cdf93fd124a9?source=rss----5c76af6b2fa7---4</link>
            <guid isPermaLink="false">https://medium.com/p/cdf93fd124a9</guid>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Eduard Krivanek]]></dc:creator>
            <pubDate>Thu, 16 Jan 2025 14:50:09 GMT</pubDate>
            <atom:updated>2025-01-16T14:50:09.274Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j9sftRts_0Z39mrzlvR_3w.png" /></figure><p>Recently, I came across the following <a href="https://www.linkedin.com/posts/roberto-heckers-2313453b_angular-activity-7274362560110379008-fFuj">dynamic service instantiation in Angular</a> from <a href="https://www.linkedin.com/in/roberto-heckers-2313453b/">Roberto Heckers</a>, where he generates a service based on some condition. Occasionally, we bump into a use case where you have multiple services, each of them sharing the same method name with a different implementation, and you want to call only one of these services based on some condition. In the following article, I decided to create a similar example and provide more use cases where dynamic service generation may be useful. This article was originally posted on <a href="https://www.angularspace.com/dynamic-service-instantiation-in-angular-2/">Angular Spaces</a>.</p><h3>Application Overview</h3><p>Let’s have an example of a money-sending application (Wise, Paysend, etc.). You want to send some amount to your friend. You are required to put the amount, the address, and select what kind of payment option you want to use. Here is the ugly version of the UI and the HTML and TS part of the form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LEuyVAJPPcW69auowndbpA.png" /><figcaption>Application Overview</figcaption></figure><pre>&lt;form [formGroup]=&quot;form&quot; (ngSubmit)=&quot;onSubmit()&quot;&gt;<br>  &lt;!-- payment amount --&gt;<br>  &lt;mat-form-field appearance=&quot;fill&quot;&gt;<br>    &lt;mat-label&gt;Amount&lt;/mat-label&gt;<br>    &lt;input matInput [formControl]=&quot;form.controls.amount&quot; /&gt;<br>  &lt;/mat-form-field&gt;<br><br>  &lt;!-- payment address --&gt;<br>  &lt;mat-form-field appearance=&quot;fill&quot;&gt;<br>    &lt;mat-label&gt;Address&lt;/mat-label&gt;<br>    &lt;input matInput [formControl]=&quot;form.controls.address&quot; /&gt;<br>  &lt;/mat-form-field&gt;<br><br>  &lt;!-- payment type --&gt;<br>  &lt;mat-radio-group [formControl]=&quot;form.controls.type&quot;&gt;<br>    &lt;mat-radio-button value=&quot;paypal&quot;&gt;Paypal&lt;/mat-radio-button&gt;<br>    &lt;mat-radio-button value=&quot;stripe&quot;&gt;Stripe&lt;/mat-radio-button&gt;<br>    &lt;mat-radio-button value=&quot;venmo&quot;&gt;Venmo&lt;/mat-radio-button&gt;<br>  &lt;/mat-radio-group&gt;<br><br>  &lt;!-- submit button --&gt;<br>  &lt;button mat-raised-button&gt;Pay&lt;/button&gt;<br>&lt;/form&gt;</pre><pre>// TS form creation<br>readonly form = new FormGroup({<br>  amount: new FormControl(0, {<br>    nonNullable: true,<br>    validators: [Validators.required, Validators.min(0)],<br>  }),<br>  address: new FormControl(&#39;&#39;, [Validators.required]),<br>  type: new FormControl&lt;&#39;paypal&#39; | &#39;stripe&#39; | &#39;venmo&#39;&gt;(&#39;paypal&#39;, {<br>    nonNullable: true,<br>    validators: [Validators.required],<br>  }),<br>});</pre><p>Nothing complicated so far. What we will be curious about is choosing the right service based on the selected option with the radio buttons.</p><h3>Multiple Service Providers</h3><p>We have 3 radio buttons — Paypal, Stripe &amp; Venmo. Each option represents one of the following services:</p><pre>@Injectable({ providedIn: &#39;root&#39; })<br>export class PaypalService extends PaymentBaseService {<br>  override pay() {<br>    // logic for payment<br>  }<br>}<br><br>@Injectable({ providedIn: &#39;root&#39; })<br>export class StripeService extends PaymentBaseService {<br>  override pay() {<br>    // logic for payment<br>  }<br>}<br><br>@Injectable({ providedIn: &#39;root&#39; })<br>export class VenmoService extends PaymentBaseService {<br>  override pay() {<br>    // logic for payment<br>  }<br>}</pre><p>There are 3 services (PaypalService, StripeService and VenmoService) which extend the PaymentBaseService that holds some common data for all of them.</p><p>Keep in mind that in real life, all these 3 payment services may bring some 3rd party library, where all of them try to connect with the provider (Stripe, Venmo, etc.) on the service instantiation. This connection establishment may be slow, it can increase the bundle size, have the potential for memory leaks, and can throw errors. Therefore we don’t want to eagerly create all these payment services, especially when only one will be needed. We want to defer the creation of only one payment service based on what option the user chooses when the form is submitted.</p><p>Also, it is worth noting that if the service is only used in a lazy-loaded component that is part of a lazy-loaded route (which is our case), an instance of the service is created only when that route is navigated, and the service is first injected to the routed component. Meaning, that even if we have 3 services registered in provideIn: &#39;root&#39;, the instance will be created only when the user navigates to the route where they are first injected.</p><h3>Dynamic Service Resolving</h3><p>As mentioned previously, we don’t want to eagerly create an instance of each payment service, as they may hold some large JS logic; instead, based on some conditions, we want to instantiate the correct one. For that, we can use Angular’s <a href="https://angular.dev/api/core/Injector">Injector</a> and do something as follows:</p><pre>type PaymentType = &#39;paypal&#39; | &#39;stripe&#39; | &#39;venmo&#39;;<br><br>@Component({<br>  selector: &#39;app-page-payment&#39;,<br>  imports: [ /* .... */ ],<br>  template: `&lt;!-- template --&gt;`,<br>  standalone: true,<br>})<br>export class PagePaymentComponent {<br>  readonly #injector = inject(Injector);<br><br>  readonly form = new FormGroup({<br>    amount: new FormControl(0),<br>    address: new FormControl(&#39;&#39;),<br>    type: new FormControl&lt;PaymentType&gt;(&#39;paypal&#39;)<br>  });<br><br>  onSubmit() {<br>    // get the payment type<br>    const type = this.form.controls.type.value;<br>    // update the payment service<br>    const paymentBaseService = this.updatePaymentService(type);<br>    // pay<br>    paymentBaseService.pay();<br>  }<br><br>  /* dynamically initialize a service by the type */<br>  private updatePaymentService(type: PaymentType) {<br>    switch (type) {<br>      case &#39;paypal&#39;:<br>        return this.injector.get(PaypalService);<br>      case &#39;stripe&#39;:<br>        return this.injector.get(StripeService);<br>      case &#39;venmo&#39;:<br>        return this.injector.get(VenmoService);<br>      default:<br>        throw new Error(`Unknown payment type: ${type}`);<br>    }<br>  }<br>}</pre><p>When the onSubmit() is executed, the updatePaymentService() method using the injector returns the correct service instance. We defer creating a service until the user chooses the type and submits the form. These payment services are created only once since they are singletons and live through the application&#39;s lifetime.</p><h3>Dynamic Service Use-Cases</h3><p>Dynamic service loading is probably not the first thing you have in mind when working on the feature. You only start to consider this option when the whole feature is a bit slow. Some real-life examples where this strategy could be useful are the following:</p><ul><li><strong>Dynamic Formatter Service</strong> — A document or data set might need to be formatted differently (e.g., JSON, XML, or CSV) based on user export preferences. You may have multiple service, each dedicated for a specific data format.</li><li><strong>File Upload Handler</strong> — When uploading files, the service handling the upload may vary based on the file type, e.g., images, videos, or documents. You create one service per uploading type. Or you may have different storing options, such as S3 for files and something else for video content.</li><li><strong>Notification Service</strong> — A system might need to send notifications via different channels such as Email, SMS, or Push Notifications, based on user preferences or settings. You can go with services such as — EmailNotificationService, SmsNotificationService, or PushNotificationService.</li><li><strong>Authentication Provider</strong> — A system might need to authenticate users against different providers like Google, Facebook, or custom enterprise SSO.</li></ul><p>All of the above mentioned examples could the below showed pattern how to dynamically instantiate a service.</p><pre>@Injectable({ providedIn: &#39;root&#39; })<br>export class AuthService {<br>  private injector = inject(Injector);<br>  private authProvider!: AuthBaseService;<br><br>  setAuthProvider(provider: &#39;google&#39; | &#39;facebook&#39; | &#39;enterprise&#39;) {<br>    switch (provider) {<br>      case &#39;google&#39;:<br>        this.authProvider = this.injector.get(GoogleAuthService);<br>        break;<br>      case &#39;facebook&#39;:<br>        this.authProvider = this.injector.get(FacebookAuthService);<br>        break;<br>      case &#39;enterprise&#39;:<br>        this.authProvider = this.injector.get(EnterpriseAuthService);<br>        break;<br>    }<br>  }<br><br>  login(credentials: any) {<br>    return this.authProvider.login(credentials);<br>  }<br>}</pre><h3>Dynamic Service Benefits</h3><p>I can’t say that this will be my go-to strategy when injecting services into a component, however, this dynamic service creation still has some benefits compared to normal injection, which is:</p><ul><li><strong>Integration with Third-Party Services</strong> — As the payment service example, each service could use some large 3rd party library, trying to establish a connection inside the constructor, and we want to avoid waiting for initialization with the 3rd party. If that service won’t be even needed, we can save time and resources.</li><li><strong>Runtime Decision Making</strong> — You may have some very dynamic applications, where a large amount of data is loaded from the user config (online Photoshop, Google Maps). You are already using dynamic components with the @defer syntax, but it can also happen that you want to distinguish which services will be created as the user may have a demo account or a paid membership account.</li><li><strong>Compliance and Customization</strong> — This goes back to the second point (runtime decision-making). For example with the payment service, you may need to create one shared payment service and then for each country create a region-specific payment gateway (service) which includes some local regulations.</li></ul><h3>Summary</h3><p>In this short article, we went through how dynamic service instantiation works in Angular, and what are the benefits and use cases where it could be considered useful. The payment code mentioned in the article is available on <a href="https://github.com/krivanek06/stackblitz-dependency-injection/tree/main/src/payment-module">Github</a>. I hope you liked the article and feel free to share your thoughts, and connect with me on <a href="https://dev.to/krivanek06">dev.to</a> | <a href="https://www.linkedin.com/in/eduard-krivanek">LinkedIn</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*m5J6uJgJu3pxrwfSQK9bqA.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdf93fd124a9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/multitude-it-labs/dynamic-service-instantiation-in-angular-cdf93fd124a9">Dynamic Service Instantiation In Angular</a> was originally published in <a href="https://medium.com/multitude-it-labs">Multitude IT Labs</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 Snap Out of Procrastination and Get Back to High Performance (Without Crying)]]></title>
            <link>https://medium.com/multitude-it-labs/how-to-snap-out-of-procrastination-and-get-back-to-high-performance-without-crying-37a51d554d08?source=rss----5c76af6b2fa7---4</link>
            <guid isPermaLink="false">https://medium.com/p/37a51d554d08</guid>
            <category><![CDATA[procrastination]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[time-management]]></category>
            <dc:creator><![CDATA[Miroslav Kudlac]]></dc:creator>
            <pubDate>Thu, 21 Nov 2024 14:16:00 GMT</pubDate>
            <atom:updated>2024-11-21T14:16:00.063Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*stZoDz6hNK83J_K4ajoXVA.jpeg" /></figure><p>We’ve all been sitting on the couch, scrolling endlessly, with that never-ending project lurking in the background like a needy ex. But guess what? Procrastination doesn’t mean you’re lazy — it just means you’re… <strong>delaying your greatness</strong>. Let’s fix that and get you back to crushing it. Here’s a fast guide to kicking procrastination’s butt — <strong>do not be oversensitive during the reading.</strong></p><h4>1. Own Your Laziness</h4><p>Step one: admit you’ve been procrastinating. Don’t worry; it’s not a moral failing — it’s just the brain avoiding pain like putting off that dentist appointment. Acknowledge you’ve been dodging your tasks and give yourself a pass. Now, we move forward.</p><h4>2. Find Your Procrastination Trigger</h4><p>There’s always a reason you’re avoiding work. Maybe the task is boring, or you’ve convinced yourself it’ll take “forever.” Or, perhaps, you’ve become a professional napper. Figure out what’s holding you back — is it fear of failure? Too many distractions? Too much Netflix? Spoiler: it’s Netflix.</p><h4>3. Set Dumb-Easy Goals</h4><p>Big, complicated tasks = a ticket to Procrastinationville. So, trick your brain. Instead of saying, <em>“I’m going to finish this 30-page report,</em>” say, <em>“I’m going to write just one paragraph.”</em> Once you start, you’ll find it’s easier to keep going. It’s like tricking a child into eating vegetables by hiding them in pizza.</p><h4>4. Make a To-Do List… and Then Throw It Away</h4><p>OK, not really. But write down everything you need to do, then pick just <strong>one</strong> most important thing. Prioritize like a pro and ignore the rest (for now). You’ll feel less overwhelmed and less likely to crawl under your desk with a snack.</p><h4>5. Use the Pomodoro Technique (aka Trick Yourself Into Working)</h4><p>Set a timer for 25 minutes, work on <strong>only one task </strong>(no doomscrolling), then take a 5-minute break to do absolutely nothing. Repeat this a few times, and voila — you’re suddenly productive. <strong>Combining this technique with others like the Eisenhower matrix, Getting Things Done, and Eat That Frog may help you</strong>. And yes, that 5-minute snack break is 100% mandatory.</p><h4>6. Banish Your Biggest Distractions</h4><p>Procrastination thrives on distractions — Instagram, emails, that bag of chips. Use apps like Cold Turkey to block your biggest time-wasters. Or, hide your phone in the fridge. Whatever it takes.</p><h4>7. Get an Accountability Buddy</h4><p>Tell someone you trust about your goals, and make them check up on you. Maybe even bribe them with coffee. Knowing someone will ask, <em>“Did you finish that thing?”</em> is surprisingly motivating. Plus, it makes you look like you have your life together.</p><h4>8. Reward Your Inner Sloth</h4><p>You did something productive! Time to celebrate. Take a nap, binge-watch a show, or buy yourself a ridiculous snack. Positive reinforcement works better than guilt trips.</p><h4>Final Thoughts: Stop Overthinking, Start Doing</h4><p>Getting back to high performance after a procrastination spree doesn’t have to be painful. Start with one small task, keep it simple, and laugh at yourself. Soon, you’ll be back to crushing your goals and wondering why you ever let procrastination slow you down in the first place. Now get to work — <strong><em>after one more snack break</em></strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37a51d554d08" width="1" height="1" alt=""><hr><p><a href="https://medium.com/multitude-it-labs/how-to-snap-out-of-procrastination-and-get-back-to-high-performance-without-crying-37a51d554d08">How to Snap Out of Procrastination and Get Back to High Performance (Without Crying)</a> was originally published in <a href="https://medium.com/multitude-it-labs">Multitude IT Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular: Go Zoneless]]></title>
            <link>https://medium.com/multitude-it-labs/angular-go-zoneless-a8824f4589e7?source=rss----5c76af6b2fa7---4</link>
            <guid isPermaLink="false">https://medium.com/p/a8824f4589e7</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[change-detection]]></category>
            <dc:creator><![CDATA[Marek Panti]]></dc:creator>
            <pubDate>Mon, 14 Oct 2024 12:25:32 GMT</pubDate>
            <atom:updated>2024-10-14T12:28:31.918Z</atom:updated>
            <content:encoded><![CDATA[<p>Angular is now entering the new Era: Zoneless Angular. In this article we will analyse how big is Zone, what it did to our apps. Then we will see the Zoneless approach and check the differences together. Personally I am very happy regarding this feature as Zone.js is very robust and now outdated system.</p><blockquote>Angular 18 with Zone, analysing bundle -&gt; implementation of a simple counter.</blockquote><h4>Angular 18 With Zone.js</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jyKxQREcjLNIGp9BCj6fEA.png" /><figcaption>Initial Angular project with zone uncompressed 113kb</figcaption></figure><h4>Angular 18 Without Zone.js</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*q-TWAzdFhnR5K-4S7K47pA.png" /><figcaption>Initial Angular App without zoneJS uncompressed 23kb</figcaption></figure><h4>Why Zoneless?</h4><p>Well, isn&#39;t it clear after those pictures? …In my opinion it might look clear, but this isn&#39;t the only advantage, there are others:</p><ul><li><strong>Better performance</strong>: ZoneJS uses async task as indicators for change. It doesn&#39;t directly know when and where exactly the change has happened. You can imagine that it is a system that always runs and is checking everything, everywhere with some exceptions such as OnPush strategy etc.</li><li><strong>Debugging</strong>: We all know the Expression Changed After Checked we&#39;ve all been there. Now the stack trace and errors will be more straight forward.</li><li><strong>Better feeling from the app: </strong>I haven&#39;t found the right words, but it just feel better. It feel better that when you change a property with async/await or using .signal(). Then the change appears immediately in the correct spot.</li><li><strong>Zone.js was the reason not to develop an App in Angular:</strong> Imagine you were building a snippet that was checking user interaction. For example you wanted to calculate how many times is user performing some event such as clicking, touching or interacting with keyboard -&gt; in such scenario your app would go crazy with Angular and you would have to have a lot of components running out of Zone and manually trigger change detection. Otherwise your app even with OnPush strategy could freeze.</li></ul><h4>The Zoneless setup</h4><p>Firstly remove zone from your .package.json file. <strong>Then do not forget to remove the Zone polyfill from Angular.json.<br></strong>Last step is to setup the bootstrapApplication without zone. For now you can check <a href="https://angular.dev/guide/experimental/zoneless#enabling-zoneless-in-an-application">https://angular.dev/guide/experimental/zoneless#enabling-zoneless-in-an-application</a></p><pre>bootstrapApplication(MyApp, {providers: [<br>  provideExperimentalZonelessChangeDetection(),<br>]});</pre><h4>How To Refactor?</h4><p>If you are following a facade architecture, mentioned in <a href="https://medium.com/javascript-in-plain-english/angular-standalone-architecture-b645edd0d54a">here</a> then you can simply start with returning signal of all of your methods instead of being observable <a href="https://angular.dev/guide/signals/rxjs-interop">https://angular.dev/guide/signals/rxjs-interop</a></p><ul><li>Convert your observables to Signals</li><li>Make sure you are not using async pipes in html, but you are refering to a signal from component or a facade</li><li>Then you can get rid of the zone and of the zone polyfill</li><li>And then you can continue to change the logic from Observables to Signals where needed</li><li>Do not forget to test all of your changes due to a different behaviour</li></ul><h4>Conclusion</h4><p>I think that Angular without Zone.JS will be more attractive for the front-end community. Zone.js negatively influenced Angular and it caused that a lot of developers moved to a different frameworks due to its bundle size and performance issues. On the other hand now Angular is becoming very attractive because it still has its unique opionated structure but at the same time it is acting as modern, performant easy to use framework.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8824f4589e7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/multitude-it-labs/angular-go-zoneless-a8824f4589e7">Angular: Go Zoneless</a> was originally published in <a href="https://medium.com/multitude-it-labs">Multitude IT Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Store Token In Http-Only Cookie]]></title>
            <link>https://medium.com/multitude-it-labs/store-token-in-http-only-cookie-239a15ea121f?source=rss----5c76af6b2fa7---4</link>
            <guid isPermaLink="false">https://medium.com/p/239a15ea121f</guid>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[token]]></category>
            <category><![CDATA[authorization]]></category>
            <dc:creator><![CDATA[Marek Panti]]></dc:creator>
            <pubDate>Tue, 08 Oct 2024 13:10:03 GMT</pubDate>
            <atom:updated>2024-10-08T13:46:49.574Z</atom:updated>
            <content:encoded><![CDATA[<p>If you need to store a token or secret information that should only be consumed by your backend and must not be accessible via JavaScript, then an HttpOnly cookie is the way to go.</p><h4>Use Case</h4><p>When searching for tutorials on handling JWT tokens in the front end, you often come across solutions where the token is stored either in local storage or a cookie. However, the issue is security. If you can access the token via JavaScript to attach it to API headers or perform other actions, there is a potential security risk. How can you avoid such issues? A good solution is to have the backend create an HttpOnly cookie, store the token inside it, and handle cookie parsing and serialization in responses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dxmC4ne5FivHdPu-jfEnBw.png" /><figcaption>I had very specific scenario to solve</figcaption></figure><h4>Specific Scenario</h4><p>I had a very specific scenario to solve: I have one front end with its own Backend for Frontend (BFF). The BFF integrates with at least five third-party services and sends data to the front end. However, I needed to integrate a specific auth server for special requests to one system already implemented in the front end, which was being called via the front end. In this situation, the best solution was using an HttpOnly cookie with SameSite=None, or using a proxy via the BFF.</p><h3>Specifications</h3><p>Firstly, let’s talk about browser storage. When learning backend development from tutorials, you often see authorization implemented using local storage. Local storage is browser storage where every tab or window has access, making it vulnerable to XSS attacks and modifications. Another option is session storage, which only exists while the tab is open — offering a bit more security, but still not ideal.</p><h4>An HttpOnly cookie, however, cannot be modified or accessed by JavaScript — meaning only the browser can attach it to requests.</h4><p>Set-Cookie:token=jwt123;SameSite=Strict;Secure;HttpOnly</p><p>You can create an HttpOnly cookie that is secure (meaning it is only sent via the HTTPS protocol), with SameSite set to Strict. The main reason for using an HttpOnly cookie is protection against CSRF and XSS attacks, as the cookie is never accessible by JavaScript.</p><p>If you want to add an HttpOnly cookie to a different origin, then SameSite should be set to None, and you need to configure the server as follows: Access-Control-Allow-Credentials: true</p><p>When using Axios (or in Angular, where httpClient doesn&#39;t use the Fetch API), you need to set: <br>withCredentials: true</p><p>You can find the full documentation regarding browsers and HttpOnly cookies <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies">here</a>, and information on cross-site communication <a href="https://developer.mozilla.org/en-US/docs/Web/Privacy/Third-party_cookies">here</a>.</p><p>Let&#39;s continue now to setup the headers, both in our front-end and the back-end.</p><h4>Headers Setup:</h4><p>Once you’ve created the cookie, you need to include it in the headers of your requests. You can only do this by setting:<br>credentials: include <br>or<br>credentials: same-origin</p><p>If you need to send the cookie cross-site, you should use value include otherwise same-origin is enough.<br>explained here: <a href="https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials">https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials</a></p><p>Then on your server side you need to accept:</p><ol><li>Access-Control-Allow-Credentials: true</li><li>Access-Control-Allow-Origin: <a href="http://my-cross-origin-url.com/">http://my-cross-origin-url.com</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers">Access-Control-Allow-Headers</a>: [..list_of_all_headers]</li></ol><h4>Issues</h4><p>This setup will send all cookies to the server each time, and on the server side, you will need to parse the cookies and find the correct one — in our case, the token.</p><h4>Conclusion</h4><p>The most secure way to store an authentication token on the front end is by using an HttpOnly cookie. There are several ways you can store the token, but you could also avoid using a token on the front end altogether by employing proxy solutions — you can proxy each request with your back-end for front-end that attaches the token for you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=239a15ea121f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/multitude-it-labs/store-token-in-http-only-cookie-239a15ea121f">Store Token In Http-Only Cookie</a> was originally published in <a href="https://medium.com/multitude-it-labs">Multitude IT Labs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>