<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Chatura Bashika on Medium]]></title>
        <description><![CDATA[Stories by Chatura Bashika on Medium]]></description>
        <link>https://medium.com/@dadcbds?source=rss-8d3713e26e69------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XG94kf3-SbMKHHVMCr5MAg.jpeg</url>
            <title>Stories by Chatura Bashika on Medium</title>
            <link>https://medium.com/@dadcbds?source=rss-8d3713e26e69------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 13:36:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dadcbds/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[SwitchMap & ConcatMap]]></title>
            <link>https://dadcbds.medium.com/switchmap-and-concatmap-885d7e9d090e?source=rss-8d3713e26e69------2</link>
            <guid isPermaLink="false">https://medium.com/p/885d7e9d090e</guid>
            <category><![CDATA[switchmap]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[concatmap]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <dc:creator><![CDATA[Chatura Bashika]]></dc:creator>
            <pubDate>Sat, 05 Aug 2023 04:16:57 GMT</pubDate>
            <atom:updated>2023-08-05T04:16:57.205Z</atom:updated>
            <content:encoded><![CDATA[<h4>Twin Brothers with a Twist!</h4><blockquote>When it comes to Reactive Programming with RxJS, two operators stand out like a dynamic duo: switchMap and concatMap. These sibling operators may appear similar at first glance, but they have distinct characteristics that make them unique. In this article, we’ll unravel the intricacies of switchMap and concatMap, exploring their similarities and uncovering the tiny yet significant differences between them. So, buckle up and get ready !</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DzhjVKz8Y7w4Dng5vyvJdA.jpeg" /></figure><p>As an Angular developer who frequently interacts with the RxJS library, I’ve often found myself pondering the differences between two perplexing operators: switchMap and concatMap. Despite my best efforts, the nuances of these operators seemed to slip from my memory after a few months. However, a simple realization eventually dawned on me: the names themselves hold the key. When I spotted “<em>switch</em>” in switchMap and “<em>concat</em>” in concatMap, it all clicked into place. Let me break it down for you.</p><h4>Map</h4><p>As it turns out, RxJS has a operator called map. Surprise, surprise! Just like its counterpart in JavaScript arrays, the map operator works by transforming the data emitted from an observable. Let’s take a closer look at this snippet of code and see the map operator in action.</p><pre>import { map, from } from &#39;rxjs&#39;;<br><br>const items = [1,2,3,4,5];<br>const mapFunc = (item: number) =&gt; item%2===0 ? <br>  `${item} is even` : `${item} is odd`;<br><br><br>// Array map<br>items.map(mapFunc)<br>.forEach(i=&gt;console.log(i))<br><br>// RxJS map<br>from(items).pipe(map(mapFunc))<br>.subscribe(i =&gt;console.log(i));</pre><pre># Results<br># Array map<br>1 is odd<br>2 is even<br>3 is odd<br>4 is even<br>5 is odd<br><br># RxJS map<br>1 is odd<br>2 is even<br>3 is odd<br>4 is even<br>5 is odd</pre><p>So how does map differ from other operators like switchMap, concatMap, or even mergeMap?</p><pre>import { map, from, of} from &#39;rxjs&#39;;<br><br>const items = [1, 2, 3, 4, 5];<br>const mapFunc = (item: number) =&gt;<br>  item % 2 === 0 ? `${item} is even` : `${item} is odd`;<br><br>const isOdd = (item: number) =&gt; of(mapFunc(item));<br><br>from(items).pipe(map((item) =&gt; isOdd(item)))<br>  .subscribe((s) =&gt; console.log(s));</pre><pre># Results<br>Observable{_subscribe: ƒ}<br>Observable{_subscribe: ƒ}<br>Observable{_subscribe: ƒ}<br>Observable{_subscribe: ƒ}<br>Observable{_subscribe: ƒ}</pre><p>This time, we have an isOdd function that splits an Observable emitting a string. Using the map operator, we attempt to map each emitted value from the array to another Observable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*I54QOpUl4WD_8jd7oEyNMQ.gif" /></figure><p>The code isn’t functioning as expected. The subscription solely subscribes to the outer Observable, completely disregarding the inner Observables.</p><blockquote>map operator applies a given project function to each value emitted by the source Observable, and emits the resulting values as an Observable.</blockquote><p>As stated in the <a href="https://rxjs.dev/api/index/function/map">RxJS docs</a>, the map operator itself doesn’t subscribe to the returned observable. It simply transforms the emitted values.</p><pre>import { from, of, concatMap} from &#39;rxjs&#39;;<br><br>const items = [1, 2, 3, 4, 5];<br>const mapFunc = (item: number) =&gt;<br>  item % 2 === 0 ? `${item} is even` : `${item} is odd`;<br><br>const isOdd = (item: number) =&gt; of(mapFunc(item));<br><br>from(items).pipe(concatMap((item) =&gt; isOdd(item)))<br>  .subscribe((s) =&gt; console.log(s));</pre><pre># Results<br>1 is odd<br>2 is even<br>3 is odd<br>4 is even<br>5 is odd</pre><p>Unlike the map operator, <a href="https://rxjs.dev/api/index/function/concatMap">concatMap</a> goes the extra mile and subscribes to the returned observables.</p><h4>Concat</h4><p>Alright folks, it’s the same drill here.</p><pre>import { from,  concat} from &#39;rxjs&#39;;<br><br>const odds = [1,3,5];<br>const evens = [2,4]<br><br>// Array concat<br>odds.concat(evens)<br>  .forEach(item =&gt; console.log(item))<br><br>// RxJS concat<br>concat(from(odds), from(evens))<br>  .subscribe(item =&gt; console.log(item))</pre><pre># Results<br># Array concat<br>1<br>3<br>5<br>2<br>4<br><br># RxJs concat<br>1<br>3<br>5<br>2<br>4</pre><p>So all concat does is create an output Observable that sequentially emits all values from the first given Observable and then moves on to the next.</p><h4>Switch</h4><p>Gotcha! There is no operator called switch in RxJS or javascript. Let’s come back to that in the switchMap.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*i4pOKJy73FZLCB-pGbuUfQ.gif" /></figure><p>Now that we have all the pieces in place, it’s time to assemble this jigsaw puzzle!</p><h4>ConcatMap</h4><p>At this point, it’s almost self-explanatory.</p><ul><li><strong>map</strong> projects each source value to an Observable</li><li><strong>concat</strong> creates output Observable which sequentially emits each Observable when the previous completes.</li></ul><p>So in simple terms conatMap will map all given Obeserveable to new Obeserveable. Which will be emited sequentially. But it waits for each one to be completed before merging the next.</p><h4>switchMap</h4><p>Interestingly enough, there isn’t actually an operator called “switch” in RxJS. So what does switchMap do?</p><pre>import { from, of, concatMap, switchMap, delay} from &#39;rxjs&#39;;<br><br>const items = [1, 2, 3, 4, 5];<br>const mapFunc = (item: number) =&gt;<br>  item % 2 === 0 ? `${item} is even` : `${item} is odd`;<br><br>const isOdd = (item: number) =&gt; of(mapFunc(item)).pipe(delay(1000));<br><br>// concatMap<br>from(items).pipe(concatMap((item) =&gt; isOdd(item)))<br>  .subscribe((s) =&gt; console.log(s));<br><br>// switchMap<br>from(items).pipe(switchMap((item) =&gt; isOdd(item)))<br>  .subscribe((s) =&gt; console.log(s));</pre><pre># Results<br># concatMap<br>1 is odd<br>2 is even<br>3 is odd<br>4 is even<br>5 is odd<br><br># switchMap<br>5 is odd<br></pre><p>In this code snipt, isOdd now has a delay of 1 second before emitting it’s value. Everything is happy and sound in the concatMap. It prints out the all the array of items. But switchMap only prints “5&quot;. What’s going on there?</p><p>Turns out, switchMap is a bit of a bandwagon fan! Unlike concatMap, switchMap has a short attention span. When a new value arrives, it quickly forgets about the previous Observable it was subscribed to and <strong>switch</strong> to the latest.</p><p>The “1&quot; emits first. Then it subscribes to isOdd(1). But before it completes, “2” is emitted down the stream. switchMap now will ditch the subscription (unsubscribes) from isOdd(1) and subscribe to isOdd(2). Likewise this will go down until “5”. After “5”, nothing is emitted down the stream. So isOdd(5) has all the time in the world to emit its value which prints out in the end.</p><h4>ConcatMap vs SwitchMap</h4><p>The only difference between the two is, concatMap doesn’t ditch when a new value is emitted while waiting. But switchMap does.</p><blockquote>switchMap will always emit the latest while conatMap emits everything.</blockquote><h3>Visualizing concatMap &amp; switchMap</h3><p>Let’s take a moment to visualize how these two operations work together. I’ve used <a href="https://rxviz.com/">Rx Visualizer</a> to create these animations for better understanding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*jVXKz1i2BtTkW15WJkDOcg.gif" /><figcaption>concatMap &amp; switchMap with 1 second delay for inner Observables. (values emited every 0.5 second)</figcaption></figure><pre>const { of, timer, from } = Rx;<br>const { delay, take, map, concatMap, switchMap } = RxOperators;<br><br>const mapFunc = item =&gt; item % 2 === 0 ? `${item} e` : `${item} o`;<br>const isOdd = item =&gt; of(mapFunc(item)).pipe(delay(1000));<br><br>// 1. values emited ervey 0.5 seconds - act as the time axis<br>const bgTimer$ = timer(0,500).pipe(<br> map(v=&gt;`${(v)/2}s`),<br> take(12),<br>)<br>// 2. concatMap with 1 second delay for inner Observables<br>const cmap$ = timer(0,500).pipe(<br> map(v=&gt;v+1),<br> take(5),<br> concatMap(isOdd)<br>)<br>// 3. switchMap with 1 second delay for inner Observables<br>const smap$ = timer(0,500).pipe(<br> map(v=&gt;v+1),<br> take(5),<br> switchMap(isOdd)<br>);<br><br>from([bgTimer$, cmap$, smap$]);</pre><p>In this setup, the timer operator emits values at regular intervals of 0.5 seconds. In concatMap, there’s a 1-second delay before emitting the first value, which corresponds to the delay caused by isOdd(1). By the time it emits, the second value “2” has already been emitted in the source stream. As a result, it takes an additional 1 second to emit the second value. This pattern continues until the end.</p><p>For switchMap, it emits “5” only after a 3 seconds . The last second represents the delay caused by the isOdd(5) function.</p><h3>The Great Angular Conundrum</h3><p>While we’re here, let’s dive into a common conundrum faced by Angular developers who rely on RxJS to fulfill their Ajax needs. It’s not so much a problem as it is a misconception. Allow me to illustrate this with a vivid example.</p><h4>Problem</h4><p>Picture this: you’re building an application for saving notes. You have a text box where users can enter their note content, and a display panel that shows what’s saved in the database. Now, when the save button is clicked, you want to store the note content in the database and fetch the saved content to display it on the panel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*gRVx7gB83GDVf2NwiQu84w.png" /><figcaption>note app</figcaption></figure><p>Behold! Here we have the code crafted by a humble Angular developer whose name, regrettably, escapes my memory 😊.</p><pre>import { Component } from &quot;@angular/core&quot;;<br>import { switchMap, tap } from &quot;rxjs/operators&quot;;<br>import { NoteService } from &quot;src/app/services/note.service&quot;;<br><br>@Component({<br>  selector: &quot;app-note&quot;,<br>  templateUrl: &quot;./note.component.html&quot;,<br>  styleUrls: [&quot;./note.component.scss&quot;],<br>})<br>export class NoteComponent {<br>  private static readonly noteId: number = 2;<br>  note: string = &quot;&quot;;<br>  savedNote: string = &quot;&quot;;<br><br>  constructor(private noteService: NoteService) {<br>    this.noteService<br>      .getNote(NoteComponent.noteId)<br>      .pipe(tap(({ content }) =&gt; (this.note = this.savedNote = content)));<br>  }<br><br>  onSave() {<br>    this.noteService<br>      .saveNote(NoteComponent.noteId, this.note)<br>      .pipe(<br>        concatMap(() =&gt; this.noteService.getNote(NoteComponent.noteId)),<br>        tap(({ content }) =&gt; (this.savedNote = content))<br>      )<br><br>      .subscribe();<br>  }<br>}</pre><p>Ah, simplicity at its finest! But, hold on a moment, there’s a catch!. We need to account for that ever-so-enthusiastic user who insists on pounding the save button. To tackle this, we must ensure that we unsubscribe from the previous requests when the user hits the save button repeatedly. So, it seems that switchMap is the perfect option, right? Simply swap out concatMap for switchMap and call it a day right?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*eMbl-eEkjEBvxPyS951xXg.gif" /></figure><p>As it turns out, when using switchMaphere, the Observable stream created still emits only one value down the stream. That’s because, for each click, a new Observable stream is created. As a result, both the save and re-fetch operations will occur undisturbed even with multiple clicks. In this case, both concatMap and switchMap behave exactly the same way. The only thing both of them guarantee is sequential execution.</p><p>It’s a common pitfall that developers can stumble upon — inadvertently slipping back into imperative thinking while working with RxJS. Although RxJS and Observables are designed to handle data streams and promote declarative and reactive programming, it’s important to remember that there’s still a potential for imperative patterns to creep in. For a deeper understanding of this topic, I highly recommend checking out “<a href="https://eliteionic.com/tutorials/imperative-vs-declarative-programming-with-rxjs-search-filter">Imperative vs Declarative Programming with RxJS</a>”¹ by <a href="https://twitter.com/joshuamorony">Josh Morony</a> and “<a href="https://www.youtube.com/watch?v=49dMGC1hM1o">Reactive Programming: Why It Matters</a>”² by <a href="https://twitter.com/andrestaltz">Andre Staltz</a>.</p><h3>Reactive and Declerative approach</h3><p>We can solve this by making the user click as a stream of events. For each click, there will be an event emitted down the steam.</p><pre>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { Subject, concat } from &#39;rxjs&#39;;<br>import {<br>  concatMap,<br>  delay,<br>  map,<br>  startWith,<br>  switchMap,<br>  tap,<br>} from &#39;rxjs/operators&#39;;<br>import { NoteService } from &#39;src/app/services/note.service&#39;;<br><br>@Component({<br>  selector: &#39;app-note&#39;,<br>  templateUrl: &#39;./note.component.html&#39;,<br>  styleUrls: [&#39;./note.component.scss&#39;],<br>})<br>export class NoteComponent {<br>  private static readonly noteId: number = 2;<br>  note: string = &#39;&#39;;<br><br>  saveEventStream$ = new Subject&lt;{ id: number; content: string }&gt;();<br>  constructor(private noteService: NoteService) {}<br><br>  note$ = this.noteService.getNote(NoteComponent.noteId);<br>  save$ = (id: number, content: string) =&gt;<br>    this.noteService.saveNote(id, content);<br><br>  savedNote$ = this.saveEventStream$.pipe(<br>    switchMap(({ id, content }) =&gt; this.save$(id, content)),<br>    startWith(this.note$),<br>    switchMap(() =&gt; this.note$),<br>    map((n) =&gt; n.content),<br>    tap((c) =&gt; (this.note = c))<br>  ); // just use async pipe in the template and Angular&#39;s got your back!<br><br>  onSave() {<br>    this.saveEventStream$.next({<br>      id: NoteComponent.noteId,<br>      content: this.note,<br>    });<br>  }<br>}</pre><p>To witness the cancellation of requests in action, you may need to adjust the network throttling settings in your browser. In this case, I have set the throttling level to <a href="https://developer.chrome.com/docs/devtools/network/reference/#throttling-profile">Slow 3G</a> to simulate a real-world scenario.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s9He1kFU0CluIKpr_CzKfA.png" /><figcaption>requests are canceling out for multiple clicks</figcaption></figure><h3>Summary</h3><p>SwitchMap and ConcatMap both serve the purpose of sequential execution. However, the key distinction lies in how they handle subscriptions. SwitchMap has a tendency to abandon the previous subscription when a new value is emitted down the stream. On the other hand, if only one value is emitted down the stream, both SwitchMap and ConcatMap will behave identically. It’s important to keep this in mind when deciding which operator to use in different scenarios.</p><p>Voilà! That’s the brotherly love between these two operators. Stay tuned for the long-lost sibling, mergeMap, on another day. Until then, adios! 👋</p><p>[1]: Morony, J. (2021). <em>Imperative vs Declarative Programming with RxJS: A Search Filter</em>. [online] Elite Ionic. Available at: <a href="https://eliteionic.com/tutorials/imperative-vs-declarative-programming-with-rxjs-search-filter/">https://eliteionic.com/tutorials/imperative-vs-declarative-programming-with-rxjs-search-filter/</a> [Accessed 19 Jul. 2023].</p><p>‌[2]: Staltz, A. (2017). <em>Reactive Programming: Why It Matters</em>. [online] <a href="http://www.youtube.com./">www.youtube.com.</a> Available at: <a href="https://www.youtube.com/watch?v=49dMGC1hM1o">https://www.youtube.com/watch?v=49dMGC1hM1o</a> [Accessed 19 Jul. 2023].</p><p><strong>All code examples at</strong> : <a href="https://github.com/melkorCBA/content-assets/tree/1cee6bff0d696b99480db165943199fcc94b8552/switchmap-vs-concatmap">github/switchmap-vs-concatmap</a>.</p><p>‌</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=885d7e9d090e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make Your Own Modal, a Fully Customizable Angular Component]]></title>
            <link>https://dadcbds.medium.com/make-your-own-modal-a-fully-customizable-angular-component-a490b9748a12?source=rss-8d3713e26e69------2</link>
            <guid isPermaLink="false">https://medium.com/p/a490b9748a12</guid>
            <category><![CDATA[customizable]]></category>
            <category><![CDATA[resize]]></category>
            <category><![CDATA[modal]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[draggable]]></category>
            <dc:creator><![CDATA[Chatura Bashika]]></dc:creator>
            <pubDate>Sat, 24 Oct 2020 16:55:52 GMT</pubDate>
            <atom:updated>2020-10-26T14:15:13.034Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*atVlW7kwgjeZA_zzNebOhw.gif" /><figcaption>Like bootstrap modal but it’s a fully customizable angular component.</figcaption></figure><p>If you are developing a SPA using angular chances are that you need a cool modal window as you see in windows explore both draggable, resizable. So to do something like that in angular we have lots of third-party libraries. A popular choice would be the bootstrap modal. But bootstrap modal doesn’t give you that functionality built-in and it’s quite hard to configure them to be draggable or resizable. Plus If you want full customization with all stylings and all other functionalities “bootstrap modal” would not be a good choice. So is there any other third-party library like bootstrap modals?. You might find a good alternative library for Bootstrap with those other features but still, it is a third-party.</p><blockquote>You might ask what’s wrong with using third-party libraries. <br>Actually, there is nothing wrong !!</blockquote><p>But,</p><p>Ah yes, there is a but. Using a third-party library means using some else code. So you can’t exceed their implementations. Also, it not always good that a critical feature of your app is depending upon another library. Most development teams spend a significant amount of time, before selecting a library. They think ahead. Meaning, for now, the library will satisfy the requirements but with Agile development is this the best choice?. Let’s take on this debate some other time. Now think that you have come to this conclusion,</p><blockquote>“Oh, this bootstrap modal is so annoying !!. Making this one draggable will be a pain in my butt. Isn’t there some way I can make a modal in angular itself?. If I make an angular component for this, It would be fully customizable.”</blockquote><p>Then this post is for you !!</p><figure><img alt="Figure 1 : Overview" src="https://cdn-images-1.medium.com/max/709/1*mtuFe_lVLpl_1-RZQL6g7Q.png" /><figcaption>Figure 1: Different route calls to the modal</figcaption></figure><p>We’ll use Angular Routing to dynamically load the modal component through the app. To get an idea have a look at this figure, where it shows you can route to the modal component anywhere in your app.</p><p>You have to use a <strong>named outlet</strong> to load the modal component and place it in app.component. (you can place it anywhere but make sure that component is a high-level component that always loads in your app). Angular can have many named outlets but one unnamed outlet in a template.</p><p>But first, let’s start from scratch.</p><p>Create an Angular app using angular CLI.</p><h3>1.Create a basic angular app</h3><pre>ng new custom-modal</pre><p>give yes to this as we’ll be needing a routing module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*8zOx_OmVgQf66U0QxHHKEg.png" /></figure><p>Here is the sketch of what we gonna build.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*GaJzn1VJCMyvRk4xjAHuOw.png" /><figcaption>Figure 2: App Design</figcaption></figure><p>So we have 4 components.</p><ol><li>app</li><li>navbar</li><li>landing</li><li>modal</li></ol><p>app.component already made for you. Let’s create the other 3.</p><pre>ng g c navbar</pre><p>use this CLI command to generate all the components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*jWSFw3LZ76Graoh8z3J3tQ.png" /><figcaption>file structure</figcaption></figure><p>Now let’s add some content to these empty components.</p><p>I have added some content and stylings for landing and navbar. Let&#39;s first place the navbar at the app component since it should visible throughout the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*yD-ja4zSbXHrn1lSUNqCWQ.png" /><figcaption>app.component.html</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tVRil1tTekK4J4R84fVz6g.png" /><figcaption>navbar view</figcaption></figure><p>Now we need to dynamically load the component according to the choice from the navbar. We are triggering route calls at the navbar and displaying it in the app component. Before that, we need to add a route to the landing page in a routing module. Add these 2 routes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4cb381eadaaeee72c1277843c7c100f/href">https://medium.com/media/b4cb381eadaaeee72c1277843c7c100f/href</a></iframe><p>Now add a primary (un-named ) router outlet in the app component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*8A6xkZpSx73wpCvXt4q7IQ.png" /><figcaption>Primary Router Outlet</figcaption></figure><p>If you hit <em>localhost:4200/</em> in the address bar of your browser you’ll see it will redirect to <em>localhost:4200/ home</em> and load the landing page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DvrfWyOmovnqf8QAKwckDA.png" /><figcaption>Figure 3: Landing page</figcaption></figure><h3>2.Modal component</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/134d9d67157e6bf4f789a00751fd0040/href">https://medium.com/media/134d9d67157e6bf4f789a00751fd0040/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7bfaeefafce60c678b538b6dd2ae6b4c/href">https://medium.com/media/7bfaeefafce60c678b538b6dd2ae6b4c/href</a></iframe><p>As you can see in the modal class I have added Z-index, so the modal is always placed above the rest of the content. Now add this secondary outlet route to load the modal component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66ceaaa5b34fc90f991039a369ea098c/href">https://medium.com/media/66ceaaa5b34fc90f991039a369ea098c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*ptx_dyOP3TwQT21Hdbu6sg.png" /><figcaption>Secondary Outlet named “panel”</figcaption></figure><p>The important thing to note here is where do you put the route for the modal. Since we gonna use this or another modal throughout the app, need to place the named outlet on a root component like app.component. You can use this outlet to load any of your customs build modal. You can use different paths to load different modals. But all of them will load to the same outlet.</p><blockquote>If you need to have modal within modal functionality, you should use another named outlet like this.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*UNQCLOJiNXJXlLneFLoR-Q.png" /></figure><p>Now let’s load it dynamically from the modal button in the landing component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9f8094f0405376150c4dc0bbda49600/href">https://medium.com/media/c9f8094f0405376150c4dc0bbda49600/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7f5647c8e2d604ef40c528bcb504b25/href">https://medium.com/media/b7f5647c8e2d604ef40c528bcb504b25/href</a></iframe><p>As you noticed we need to inject the Angular router into our constructor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fzBRLD231aXfOHyW7RHlQA.png" /><figcaption>Figure 4: Loaded Modal</figcaption></figure><p>You’ll see some weird text in the address bar. You can remove this by using the <strong>skipLocationChange </strong>option of navigation extras. By using this we can prevent the panel route from going to the browser history.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*zcvtPTGHisxgFYRmPIQ91g.png" /><figcaption>set skipLocationChange to True</figcaption></figure><p>Now let’s close the modal.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1243f7afc424705a98919ef8dd538137/href">https://medium.com/media/1243f7afc424705a98919ef8dd538137/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/011fdf15608f625efc921d4d692d49d2/href">https://medium.com/media/011fdf15608f625efc921d4d692d49d2/href</a></iframe><h3>3.Make it draggable</h3><p>To archive this I am using the angular material drag and drop module. If you want to you can refer to <a href="https://medium.com/swlh/create-a-resizable-and-draggable-angular-component-in-the-easiest-way-bb67031866cb">this</a> article to build your own custom draggable functionality.</p><p>first, let’s install angular materials Into our app.</p><pre>ng add @angular/material</pre><p>to make a div container draggable, we need to add cdkDrag directive to the div. You also need to import DragDropModule to our App module and export it so we can use it anywhere.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa382646823ab91f74af93b2647530c6/href">https://medium.com/media/fa382646823ab91f74af93b2647530c6/href</a></iframe><p>now add the directive</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08d8756d6c733e74088939c3e08bb4cc/href">https://medium.com/media/08d8756d6c733e74088939c3e08bb4cc/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*vYAAuDzqc86WGO0o-cmwvw.gif" /><figcaption>Figure 5: Draggable Modal</figcaption></figure><h3>3.Make it resizable</h3><p>This is implemented using the same technic in <a href="https://medium.com/swlh/create-a-resizable-and-draggable-angular-component-in-the-easiest-way-bb67031866cb">this</a> article and this <a href="https://stackblitz.com/edit/ngx-cdk-drag-resize">demo</a>. You might have to tweak the styling a bit to position the drag handles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*BKszCcvur8-_uEIRjGAWIQ.gif" /><figcaption>Figure 6: Resizable modal</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec47a9bf34fa10a826272a2ee0c111a4/href">https://medium.com/media/ec47a9bf34fa10a826272a2ee0c111a4/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9b01902ab98777a99803319cc0d3ab0/href">https://medium.com/media/a9b01902ab98777a99803319cc0d3ab0/href</a></iframe><h3>4.Add a backdrop</h3><p>We’ll create a separate component to implement backdrop. Let&#39;s call it backdrop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*E22u24ovtLhBfI3y3H3yZQ.png" /><figcaption>backdrop template</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4e48d0667a7a074ce38c3971a901f72/href">https://medium.com/media/f4e48d0667a7a074ce38c3971a901f72/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*ndeON0h5pgP5AvjlXoP_vg.png" /><figcaption>Backdrop styling</figcaption></figure><p>We have added an event binding to catch the event when the user clicks on the backdrop. Will capture this event and close the modal. We will place this backdrop in the modal component like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdbae0ae1510a63cb35021c3f2599d95/href">https://medium.com/media/bdbae0ae1510a63cb35021c3f2599d95/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*bMcsz_fLk7rLWvHM_t7uKA.gif" /><figcaption>Figure 7: Modal with the backdrop</figcaption></figure><h3>Handling multiple routing calls</h3><p>There may be a case where you need to close the modal and navigate to another route. So you may be thinking of a code like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*hSYHVuOIxF-UVErsfIPgRg.png" /><figcaption>multiple route calls</figcaption></figure><p>But it won’t work. Angular will ignore the first call. The modal will be closed but you won’t be navigated to another route. But since <em>router.navigate</em> returns a promise you can use something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*ubfdd2V-vzjpTdxJ5S6wbA.png" /><figcaption>handle multiple route calls</figcaption></figure><p>Also if you are lazy loading your components, you may have to do this to close the modals. If you make the panel null it won’t open again. Make sure to inject Location service in <em>“@angular/common” </em>to your constructor.</p><pre>this.router.navigate([this.location.path(false)],{replaceUrl:true});</pre><h3>Conclusion</h3><p>It may seem a lot of work but in the end, you have full control over the modal. There are some things you can do to make this more reusable. Maybe you can create a common angular service to handle modal open/close actions. A boilerplate code to wrap the reusable HTML content around the modal contents. The only overhead is you have to add a new route to the routes array for each modal.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a490b9748a12" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>