<?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 AG Dev on Medium]]></title>
        <description><![CDATA[Stories by AG Dev on Medium]]></description>
        <link>https://medium.com/@agdev-tech?source=rss-e17a654513f4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bUKqCSMRao0FC8X3_AI5gw.png</url>
            <title>Stories by AG Dev on Medium</title>
            <link>https://medium.com/@agdev-tech?source=rss-e17a654513f4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 15:45:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@agdev-tech/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[ANGULAR GUARDS IN DISNEYLAND PARK]]></title>
            <link>https://agdev-tech.medium.com/angular-guards-in-disneyland-park-7ae97d7d6759?source=rss-e17a654513f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ae97d7d6759</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[routing]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-guards]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[AG Dev]]></dc:creator>
            <pubDate>Sun, 08 Aug 2021 10:14:44 GMT</pubDate>
            <atom:updated>2021-08-09T07:01:56.510Z</atom:updated>
            <content:encoded><![CDATA[<p>In an Angular application you might need to run some checks before allowing the user to navigate <strong>to </strong>or <strong>away </strong>from a page. That’s where <strong>Angular Guards </strong>come into play.</p><p>The picture below displays how guards work. A user is trying to navigate in the application, but before allowing navigation there is a guard that is running some checks and then the guard can decide for the next steps: allow the user or not to navigate, display a confirmation/information dialog or even redirect the user somewhere else.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/0*4LMlml4fWs0v62Np" /></figure><p>For this guide we will take a trip into Disneyland, Walt Disney and Disney Park. As we pass guards we discuss what they are checking and how they are implemented by giving a full picture of Guards.</p><p>We just arrived at the main entrance of the Park and we see a guard waiting to check our ticket. If we have a ticket and it’s valid, the Guard will allow us to enter the park.</p><p>Now let’s see how we can implement it. We have a component called Disneyland and we want the guests to access this component only when they are authenticated, have a valid token in a real case scenario or a valid ticket in our case. We want to prevent the users from accessing this component either by a navigation link or through URL access. When the user opens the app, a form to enter the ticket is displayed as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/0*OKzJm9u4mBgeodE_" /></figure><p>According to <a href="https://angular.io/api/router/CanActivate">Angular Documentation</a> CanActivate is an interface that a class can implement to be a guard deciding if a route can be activated.</p><p>With this in mind we implement our TicketGuard as below:</p><pre><strong>@Injectable({ providedIn: &#39;root&#39;, })</strong> <br>export class <strong>TicketGuard </strong>implements <strong>CanActivate </strong>{ <br>  <br>    constructor( private disneyService: DisneyService, private   snackBar: MatSnackBar ) {<br>}</pre><pre><strong>canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot)</strong> { <br>    const ticket = this.disneyService.getTicket(); <br>    const isValid = ticket &amp;&amp; ticket.startsWith(&#39;D&#39;); <br>    if (!isValid) { <br>      this.snackBar.open(&#39;Your ticket is not valid!&#39;, &#39;OK&#39;); }      return isValid; <br>  } <br>}</pre><p>We are checking that the user has a ticket and this ticket should start with D to be valid. Now it’s time to add this guard in our route as below:</p><pre>const routes: Routes = [ <br>      { path: &#39;home&#39;, component: GuardsHomeComponent},  <br>      { <strong>path: &#39;disneyland&#39;</strong>, component: DisneyComponent,<br>        <strong>canActivate: [TicketGuard],</strong> <br>       }, <br>       {path: &#39;&#39;, redirectTo: &#39;home&#39;, pathMatch: &#39;full&#39;}, <br> ];</pre><p>Let’s suppose that once you enter the main entrance there are some shops and cafes and two other entrances, Walt Park and Disney Park. Each of these park should be available once you enter at the main entrance.</p><p>For this case we need to handle protecting nested routes, both park-walt-component and park-disney-component are nested inside disneyland-component. We could use CanActivate for each of these components, but we follow <strong>DRY</strong>.</p><p>According to <a href="https://angular.io/api/router/CanActivateChild">Angular Documentation</a> CanActivateChild is an interface that a class can implement to be a guard deciding if a child route can be activated.</p><p>We will be using the same guard and will update the above TicketGuard to implement the CanActivateChild Interface and the route protection is implemented as below:</p><pre>const routes: Routes = [ <br>{path: &#39;home&#39;, component: GuardsHomeComponent}, <br>{<br>  path: &#39;disneyland&#39;, <br>  component: DisneyComponent, <br>  canActivate: [TicketGuard], <strong> <br>  canActivateChild: [TicketGuard],</strong> <br>  children: [ <br>   { path: &#39;park&#39;, component: ParkDisneyComponent, }, <br>   { path: &#39;walt&#39;, component: WaltDisneyComponent, } ] }, <br>   { path: &#39;&#39;, redirectTo: &#39;home&#39;, pathMatch: &#39;full&#39;}, <br>];</pre><p>Time after time some rides are under maintenance. In case all the rides of the park are under maintenance we do not want to allow the user to enter there, but instead redirect to the nice shops and cafes. We also want to show the user a list of all the available rides once he enters inside one of the parks.</p><p>According to <a href="https://angular.io/api/router/Resolve#description">Angular Documentation</a>, Resolve is an interface that classes can implement to be a data provider, which can be used with router to resolve data during navigation.</p><p>By implementing Resolve guard we will fetch the rides for the selected park and if all rides are under maintenance we will redirect the user to the park, if not we will redirect him to the Disneyland.</p><pre><strong>@Injectable({ providedIn: &#39;root&#39;, })</strong> <br>export class <strong>RidesResolverService </strong>implements <strong>Resolve&lt;Ride[]&gt;</strong> { </pre><pre> constructor( <br>        private disneyService: DisneyService, <br>        private router: Router, <br>        private snackBar: MatSnackBar ) {}</pre><pre><strong> resolve</strong>(<br>   route: ActivatedRouteSnapshot, <br>   state: RouterStateSnapshot): <br>   Observable&lt;Ride[]&gt; | Observable&lt;never&gt; { <br>   <br>   const url = state.url; <br>   const park = url.indexOf(&#39;park&#39;) &gt; -1 ? DISNEY.PARK : DISNEY.WALT; </pre><pre> return this.disneyService.getRides(park).pipe( <br>     take(1), <br>     mergeMap(rides =&gt; { <br>         if (rides?.length &gt; 0) {<strong> <br>             return of(rides);</strong> <br>         } else <br>  { <br>        this.snackBar.open(&#39;Currently all the rides are in   maintenance, enjoy the DISNEY shops!&#39;, &#39;OK&#39;);<strong> <br>this.router.navigate([&#39;guards&#39;, &#39;disneyland&#39;]); return EMPTY;</strong> } }) ); } }</pre><p>And inside any of the parks we will get the list of rides by routing as below:</p><pre>this.route.data .subscribe((data: { rides: Ride[] }) =&gt; <br>     { <br>         this.rides = data.rides; <br>});</pre><p>Next we need to configure resolve in both park routes as below:</p><pre>children: [ <br>    { <br>       <strong>path: &#39;park&#39;</strong>, <br>       component: ParkDisneyComponent,<strong> <br>       resolve: { <br>           rides: RidesResolverService <br>        }</strong> }, <br>     {<br>         <strong>path: &#39;walt&#39;</strong>, <br>         component: WaltDisneyComponent,<strong> <br>         resolve: { <br>            rides: RidesResolverService <br>      }</strong> <br>}</pre><p>After a guest enters one of the parks, before leaving we might want to make sure that he experienced all the magic: visited a castle or took some rides. In case he did not do any we want to ask him if he is sure that he wants to leave and once we get the confirmation allow him to leave the park.</p><p>Brought in a real life scenario, after the user has filled a large and complex form with data, before allowing him to navigate away in case the form was not saved, we might want to make sure if the user is purposely navigating away or it is by mistake.</p><p>According to <a href="https://angular.io/api/router/CanDeactivate">Angular Documentation</a>, CanDeactivate is an interface that a class can implement to be a guard deciding if a route can be deactivated.</p><p>Our guard will look like this:</p><pre><strong>@Injectable({ providedIn: &#39;root&#39;, })</strong> <br>export class <strong>CanDeactivateGuard </strong>implements   <strong>CanDeactivate&lt;CanComponentDeactivate&gt;</strong> {</pre><pre><strong>    canDeactivate</strong>(component: CanComponentDeactivate) { <br>      const canDeactivate = component.canDeactivate ?   component.canDeactivate() : true; return canDeactivate; <br>} }</pre><p><em>canDeactivate </em>function implemented in each of the parks looks like this:</p><pre><strong><em>canDeactivate</em></strong>(): Observable&lt;boolean&gt; | boolean { <br>    if (this.experiencedDisney) { <br>        return true; <br>     } </pre><pre>const confirmation = window.confirm(&#39;You sure you want to leave Walt  Disney without experiencing it?&#39;); <br>         return of(confirmation); <br>}</pre><p>Next step is to configure the CanDeactivate Guard inside each of the paths:</p><pre>{ <br>   path: &#39;park&#39;, <br>   component: ParkDisneyComponent, <strong> <br>   canDeactivate: [CanDeactivateGuard],</strong> <br>   resolve: { <br>      rides: RidesResolverService <br>} },</pre><p>Last guard we will have a look is CanLoad, which prevents the loading of a LazyLoadedModule. While CanActivate is protecting the route, through CanLoad Guard we can protect the performance, by not loading modules in the browser that can not be activated. The implementation and configuration of CanLoad Guard follows the same structure as CanActivateGuard, but it’s applied on the lazy loaded modules instead of path.</p><p>This was a short guide in Angular Guards, their functionalities, implementation and configuration. If you have any question or any idea on how to improve it, please do not hesitate to reach out.</p><p><em>Originally published at </em><a href="https://agdev.tech/2021/08/08/angular-guards-in-disneyland-park/"><em>http://agdev.tech</em></a><em> on August 8, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ae97d7d6759" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Authentication, Interceptors and Guards]]></title>
            <link>https://agdev-tech.medium.com/angular-authentication-interceptors-and-guards-d234cfb12260?source=rss-e17a654513f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/d234cfb12260</guid>
            <category><![CDATA[security-guards]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[interceptors]]></category>
            <dc:creator><![CDATA[AG Dev]]></dc:creator>
            <pubDate>Thu, 18 Mar 2021 17:58:51 GMT</pubDate>
            <atom:updated>2021-03-19T06:44:54.299Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article I will create step by step an Authentication library and along the way will describe Interceptors and Guards.</p><p><strong>Application Description</strong></p><p>This application will have these pages: Login, Home, User Dashboard and Admin Dashboard which will have different access levels as described in the table below.</p><p>For the implementation we will need an Angular Application that you can set up following these steps:</p><ol><li>ng new auth-demo Create a new Angular Application</li><li>ng g lib authentication Generate the authentication library</li><li>ng g c home Generate the Home Component</li><li>ng g c user-dashboard Generate the User Dashboard Component</li><li>ng g c admin-dashboard Generate the Admin Dashboard Component</li></ol><p>At this point we have already set up the application and will start working on the Authentication Library.</p><p>**You can find the demo in <a href="https://stackblitz.com/edit/agdev-authentication-r4u9f5?file=src/app/authentication/authentication.service.tshttps://stackblitz.com/edit/agdev-authentication-r4u9f5?file=src/app/authentication/authentication.service.ts">this stack blitz</a>. The only difference is that Authentication is a module instead of a library. The implementation will consider Authentication as a library, which means that it can be used everywhere and has no dependencies from the current app.</p><p><strong>Authentication Library</strong></p><p>Let’s start first by implementing the Login and Logout components. Login component will contain a form with username and password and logout will contain a button. Authentication Service will be responsible to manage the login, logout and checking if the user is authenticated.The scheme below shows how we will handle the login and logout.</p><p>For this demo I have implemented a simple mock backend service, where two users are provided: <strong>admin/admin</strong> and <strong>user/user</strong>.</p><p>As you will see in the implementation, we need to inject both the authentication endpoint and the initial page to be loaded after the user has been logged in. In order to make the library independent we inject them in the Authentication Module:</p><pre>export class AuthenticationModule { <br>   static forRoot(config: LibraryConfig): ModuleWithProviders&lt;AuthenticationModule&gt; { <br>     return { ngModule: AuthenticationModule, <br>     providers: [{provide: &#39;config&#39;, useValue: config}] }; <br>   }<br>}</pre><p>And then wherever we import it our apps we specify this config value as below:</p><pre>export const AUTHENTICATION_CONFIG = <br>  { authEndpoint: &quot;/users/authenticate&quot;, initialPage: &quot;home&quot; };</pre><pre>imports: [ AuthenticationModule.forRoot(AUTHENTICATION_CONFIG) ]</pre><p>This will ensure that the library will not change anything when one of these parameters needs to be adapted.</p><p><strong>JWT Token</strong></p><p>JSON Web Tokens are an open, industry standard for representing claims securely between two parties. When we dispatch a successful login request in a real word application, the backend would send us back a token. After that, we have established a secure connection between frontend and backend. With each request that the frontend will send to the backend we need to attach this token. Token can contain different types of information and it also can expire. At this point we can start explaining and implementing the TokenInterceptor.</p><p><strong>Interceptor</strong></p><p>According to <a href="https://angular.io/api/common/http/HttpInterceptor">Angular Documentation</a>: “An Interceptor handles an HttpRequest or HttpResponse before passing to the next interceptor in the chain, by calling next.handle(transformedReq)”. So what an Interceptor basically does is to “listen” for either a request or response and transform the data or produce a side effect. I will implement two interceptors as below:</p><p><strong>HttpRequest Interceptor</strong></p><p>Inside the Authentication library, I have created the Token Interceptor. As we defined above, this interceptor will listen to any HttpRequest and will attach the token to the header of the request as below:</p><pre>@Injectable() <br>export class TokenInterceptor implements HttpInterceptor { </pre><pre>constructor( private authenticationService: AuthenticationService) { } </pre><pre>intercept(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; { <br>let user = this.authenticationService.getLoggedUser();<br>if (user &amp;&amp; user.token) { <br>    request = request.clone({ setHeaders:<br>          { Authorization: `Bearer ${user.token}` } }); } <br> return next.handle(request);  <br>  } <br>}</pre><p>So this interceptor is getting the token of the logged user and attaching it to the header of the request. In this way the backend can validate the request and bring to the front end the result.</p><p><strong>HttpResponse Interceptor</strong></p><p>The second interceptor will listen to any incoming response and then will respond accordingly. Let’s suppose the token that the backend has generated expires, so even though we send the request and attach successfully the token, the backend brings us a 401 error (unauthorized user). In this case we should detect this error and automatically logout the user.</p><pre>@Injectable() <br>export class ErrorInterceptor implements HttpInterceptor { </pre><pre>constructor(private authentiationService: AuthenticationService) { } </pre><pre>intercept(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; { <br>     return next.handle(request).<br>              pipe(catchError(err =&gt; { <br>      if (err.status === 401) {      <br>          this.authentiationService.logout();<br>          location.reload(); } <br>          const error = err.error.message || err.statusText; <br>          return throwError(error); <br>    }))<br> } <br>}</pre><p>After successfully implementing the interceptors we need to provide them inside the Authentication Module as below:</p><pre>providers: [ <br>{ provide: HTTP_INTERCEPTORS, useClass: TokenInterceptor, <br>  multi: true }, <br>{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor,<br>   multi: true} <br>]</pre><p>After implementing the interceptors, the next step is to implement Guards.</p><p><strong>Guards</strong></p><p>As we have described above, different users will have different access in the app. We will implement the CanActivate Interface from @angular/router which will decide if a route can be activated. To fulfill our requirements we will need two types of guards:</p><ol><li>AuthenticationGuard -&gt; check if the user is authenticated and allow him to access Home</li><li>RoleGuard -&gt; check if the user has permission to access User or Admin Dashboard.</li></ol><p><strong>Authentication Guard</strong></p><p>This Guard will do a simple check if the user is authenticated which means we have locally stored a token for this user. The implementation is as below.</p><pre>@Injectable({ providedIn: &#39;root&#39; }) <br>export class AuthenticationGuard implements CanActivate {</pre><pre> constructor( <br>     private router: Router, <br>     private authenticationService: AuthenticationService ) {<br> }</pre><pre> canActivate(<br>    route: ActivatedRouteSnapshot, <br>    state: RouterStateSnapshot) {  <br>    const currentUser = this.authenticationService.getLoggedUser(); <br> <br>    if (currentUser) { <br>         return true; <br>     }<br>   this.router.navigate([&#39;/login&#39;]); return false; } <br>}</pre><p>In case the user is not logged in, we are simply redirecting him to login page.</p><p><strong>Role Guard</strong></p><p>For this case, the mock back end I have provided saves the role in the token. Which means the value of our token will be either user or admin. The token will be more complicated in your application, but this is a basic idea. This will be the implementation of our RoleGuard.</p><pre>@Injectable({ providedIn: &#39;root&#39; }) <br>export class RoleGuard implements CanActivate { </pre><pre>constructor( <br>    private router: Router, <br>    private authenticationService: AuthenticationService ) { <br>} </pre><pre>canActivate(<br>     route: ActivatedRouteSnapshot,  <br>     state: RouterStateSnapshot) { <br>const currentUser = this.authenticationService.getLoggedUser();  const expectedRole = route.data.expectedRole; </pre><pre>if (currentUser.token === expectedRole) { <br>     return true; <br>} <br> this.router.navigate([&#39;/home&#39;]); <br> return false;  <br>   }<br> }</pre><p>After implementing the permission guard in order to make this work we need to set up routes for the component and specify the guards that will protect them as I have defined them in app-routing.module:</p><pre>const routes: Routes = [ <br> {path: &#39;login&#39;, component: LoginComponent}, <br> {path: &#39;home&#39;, component: HomeComponent,<br>         canActivate: [AuthenticationGuard]}, <br>{path: &#39;admin&#39;, component: AdminDashboardComponent,<br>        canActivate: [AuthenticationGuard, RoleGuard], <br>        data: {expectedRole: ROLE.ADMIN}}, <br>{path: &#39;user&#39;, component: UserDashboardComponent, <br>        canActivate: [AuthenticationGuard, RoleGuard], <br>        data: {expectedRole: ROLE.USER}}, <br>{path: &#39;**&#39;, component: NotFoundComponent} <br>];</pre><p>So we can see, that in order to access the Home Component route the user needs just to pass the Authentication Guard, while AdminDashboard and UserDashboard can only be activated when the user is authenticated and has the role user/admin that the route is expecting.</p><p>You can go and check the implementation in this <a href="https://stackblitz.com/edit/agdev-authentication-r4u9f5?file=src/app/app-routing.module.ts">stack blitz link</a> or run the application in this <a href="https://agdev-authentication-r4u9f5.stackblitz.io/">link</a>.</p><p><strong>Conclusions</strong></p><p>To sum up we implemented an application with some components that can be activated by specific users. We implemented the Authentication Library, which can be used in different applications because we are providing it with all the information it needs such as authentication endpoint and initial route when login is successful. We went over JWT authentication, Interceptors and Guards. In different scenarios you might need to adapt the authentication according to your needs, but these are the key concepts related to it.</p><p><em>Originally published at </em><a href="http://agdev.tech/2021/03/18/angular-authentication-interceptors-and-guards/"><em>http://agdev.tech</em></a><em> on March 18, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d234cfb12260" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Queue And Priority Queue in typescript]]></title>
            <link>https://agdev-tech.medium.com/queue-and-priority-queue-in-typescript-deaaf4a2c7ed?source=rss-e17a654513f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/deaaf4a2c7ed</guid>
            <category><![CDATA[queue]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <dc:creator><![CDATA[AG Dev]]></dc:creator>
            <pubDate>Tue, 09 Mar 2021 10:37:09 GMT</pubDate>
            <atom:updated>2021-03-09T10:57:54.799Z</atom:updated>
            <content:encoded><![CDATA[<h3>Queue And Priority Queue in Typescript</h3><p>In this article I will first implement a queue in typescript and will display data saved in the queue using Angular. Later on I will talk about priority queues and implement it using a similar logic. The idea is to display another type of queue where the elements will have a priority which will determine who will be pulled first.</p><p>Queue is a <strong>FIFO </strong>(First In First Out) data structure. Let’s think of a group of customers in the shop waiting to buy coffee. The one who arrived first will be served first. All the customers arriving will be waiting at the end of the line until everyone who came before will be served.</p><p><strong>Queue Terminology and Operations</strong></p><ol><li><strong>enqueue: </strong>Add a new element at the collection.</li><li><strong>dequeue</strong>: Remove and returns the least recently-added element.</li><li><strong>peek: </strong>Retrieve the least recently-added element without removing it.</li><li><strong>isEmpty</strong>: Checks if the collection has no elements.</li></ol><p>When implementing a queue it is important that all the operations should be executed in constant time, O(1) complexity. With that being said, contrary to stack, we can not use arrays to implement a queue because either in enqueue or dequeue we will have to shift the elements so the complexity will be O(N).</p><p>For the above mentioned reasons I have implemented a generic Queue using Linked List. This is the node definition:</p><pre>export class Node&lt;T&gt; { <br>   value: T; <br>   next: Node&lt;T&gt;; <br>}</pre><p>Each node has a value and a pointer to the next node. Here is the Queue implementation:</p><pre>export class Queue&lt;T&gt; { <br>   private head: Node&lt;T&gt;; <br>   private tail: Node&lt;T&gt;; <br>   <br>   public enqueue(value: T): Node&lt;T&gt; { } <br>   public dequeue(): Node&lt;T&gt; { } <br>   public peek(): T { } <br>   public isEmpty(): boolean { } <br>   public get data(): [] { } <br>}</pre><p>As we can see the queue includes all the operations such as enqueue, dequeue, peek and a check if the queue is empty. I have also added a method to get data so that I can display them in the application. Since adding and removing new elements of the queue needs to be done in constant time we need to keep track of the head and the tail of the linked list. When adding new elements the tail will be updated and when removing the head will be updated.</p><p>You can find the queue implementation in this <a href="https://stackblitz.com/edit/angular-ivy-ba9qye?file=src%2Fapp%2Fqueue-visualization%2Fqueue%2Fqueue.ts">Stack Blitz Link</a>. I have also displayed the queue state after each operation as below. As you will see, by clicking the Enqueue button new elements will be added at the end of the queue and by clicking Dequeue the first added elements will be removed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/221/0*9CG38ImNFVXgzcnE" /></figure><p><strong>Priority Queue</strong></p><p>The above explanation works where the client to be served is the next in line. Let’s suppose there is a rule that indicates the elder people have a higher priority to be served first. At this moment, regardless of the time they came, the oldest will be getting their coffee first. The above implementation can not be used for this case.</p><p>A priority queue is an abstract data type in which each element has additionally a priority associated with it. In a priority queue, an element with higher priority will be served before an element with lower priority.</p><p>If we consider the coffee example, the age will be the priority to determine who will get the coffee first. There are different kinds of implementations for the priority queue. First is using a sorted list, whenever a new element is added it will check the position to be inserted considering the priority. Secondly you can implement it using an unordered list, but when a dequeue happens it will check which element to remove by priority assigned. The third implementation is using a heap. I have chosen the first implementation. Each of them have different advantages in add and remove elements as below.</p><p>Let’s analyze the first implementation. When adding a new element in a sorted list we will need to iterate all the elements until we find it’s correct position. For this reason insertion takes linear time. While removing elements is constant because the element with the higher priority will be at the beginning of the list.</p><p><strong>Priority Queue Implementation using Sorted Linked List</strong></p><p>The difference between the priority queue and queue nodes, will be that the first will need to keep track of the priority value. So the node definition will be:</p><pre>export class PriorityNode&lt;T&gt; { <br>    value: T; <br>    priority: number; <br>    next: PriorityNode&lt;T&gt;; <br>}</pre><p>Again the priority queue will define all the operations like: enqueue, dequeue, peek, and is empty. The enqueue will now include managing the insertion at the right position. Here is the definition:</p><pre>export class PriorityQueue&lt;T&gt; { <br>   private head: PriorityNode&lt;T&gt;; <br>   private tail: PriorityNode&lt;T&gt;; </pre><pre>   public enqueue(value: T, priority: number): PriorityNode&lt;T&gt; { }    <br>   public dequeue(): PriorityNode&lt;T&gt; {} <br>   public peek(): T { } <br>   public isEmpty(): boolean { } <br>   public get data() { } <br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/0*Y5tAhHOjIWo5Dt-I" /></figure><p>As you will see, by clicking the Enqueue button new elements will be added to the collection and by clicking Dequeue the one with the higher priority will be removed. As you can see even why a new customer with age 92 came last, he will be served first because age is the priority in this case.</p><p>In the <a href="https://stackblitz.com/edit/angular-ivy-ba9qye?file=src%2Fapp%2Fqueue-visualization%2Fpriority-queue%2Fpriority-queue.ts">Stack Blitz Link</a> you can see the code and the behaviour of priority queue, otherwise if you want to access only the application where you could see the queue and priority queue behaviour you could go here: <a href="https://angular-ivy-ba9qye.stackblitz.io/">Stack Blitz App</a>.</p><p><strong>Conclusions</strong></p><p>To sum up, we created a new queue using Typescript and then visualized the operations using Angular. After a detailed explanation we went over the priority queue and its implementation in Typescript using sorted list. Hope you found this article helpful and let me know your thoughts.</p><p><em>Originally published at </em><a href="http://agdev.tech/2021/03/09/queue-and-priority-queue-in-typescript/"><em>http://agdev.tech</em></a><em> on March 9, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=deaaf4a2c7ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stack Data Structure in Typescript]]></title>
            <link>https://agdev-tech.medium.com/stack-data-structure-in-typescript-9f96527693a5?source=rss-e17a654513f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f96527693a5</guid>
            <category><![CDATA[stack]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[AG Dev]]></dc:creator>
            <pubDate>Tue, 02 Mar 2021 13:34:33 GMT</pubDate>
            <atom:updated>2021-03-02T15:16:40.031Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article I will implement a stack in typescript and will display data saved in stack using Angular. Later on we will use this stack to solve the problem where we need to check if a string of parenthesis is balanced.</p><p>Stack is a LIFO (Last In First Out) data structure. Let’s think of a stack of books. Adding a new book will place that on top of the stack and removing books will be from the top of the stack. So in order to take a specific book, we have to remove all the elements on top of it.</p><p><strong>Stack Terminology and Operations</strong></p><ol><li><strong>push: </strong>Add a new element on top of the stack.</li><li><strong>pop </strong>: Remove the last added element.</li><li><strong>peek: </strong>Retrieve the top element without removing it.</li><li><strong>size</strong>: Total number of elements in the stack.</li><li><strong>isEmpty</strong>: Checks if the stack has no elements.</li></ol><p>By default typescript has a built-in Stack, but for this article I will create everything from scratch. The idea behind stack is that all the operations should be executed in constant time: O(1) complexity.</p><p>To implement a Stack in Typescript, we are going to create a new generic class named Stack and all the operations that we mentioned above.</p><pre>export class Stack&lt;T&gt; { <br>    private _data: T[] = []; </pre><pre>    push(value: T): void {} </pre><pre>    pop(): T {} </pre><pre>    peek(): T {} </pre><pre>    size(): number {} <br> <br>    isEmpty(): boolean {} <br>}</pre><p>You can find the stack implementation here: <a href="http://Stackblitz%20Link"><strong>https://stackblitz.com/edit/angular-ivy-bmbned?file=src/app/stack-visualization/stack.ts</strong></a><strong>. </strong>I have also included a simple UI that allows you to push and pop dynamically generated values in the stack. Also the stack display the peek value of the stack or a message if the stack is empty as below:</p><p><strong>Custom stack implementation</strong></p><p>We mentioned before that all the stack operations complexity is constant and Typescript offers a built-in stack implementation. The question that might arise is when do we need to implement a custom stack. Let’s say you have to keep track of the maximum value at every moment in the stack. If after each operation of push and pop we have to display the maximum value and we check all the values to get the maximum, the time complexity of our stack will be O(n). An efficient solution is to keep a maxStack and after each push we will do a comparison between the peek value of maxStack and the new value and after each pop we will just pop the value from both stacks. At every moment the maximum value in our stack can be accessed by using peek in maxStack.</p><p>Stack can be implemented using either a Linked List, an Array or Dynamic Array. For this case I chose the dynamic array implementation. All the implementations have their advantages and disadvantages. Using a linked list to implement the stack will add on overhead because we will need to keep track of the next node, but on the other hand we will not block the memory for a stack that might not need all that. If we chose to implement the stack with a fixed size array we risk allocating more/less memory than the stack needs because we might not be aware beforehand how many elements the stack will keep. Dynamic Arrays is an elegant solution, because it will check if the array is almost full and will increase the space dynamically and this cost will be amortized.</p><p><strong>Balanced Parenthesis Solution</strong></p><p>Let’s suppose we have a string of parenthesis and we need to check if the string is balanced. Balance means that there is a matching closing parenthesis for every opening parenthesis and they are in order.</p><p>{[]} -&gt; String is balanced because in the exact order for each opening parenthesis is a closing one.</p><p>{{]} -&gt; String is not balanced because the second { is not closed correctly.</p><p>In order to solve this problem, we first need to understand it and why stack is the data structure that provides us with the optimal solution.</p><p>For each opening parenthesis we need to have a closing one is the exact order in order for the string to be balanced. Basically we need to keep track of all the opening parenthesis: <strong>{([</strong> and when we encounter a closing parenthesis <strong>})] </strong>we need to check if that is matching with the last opening parenthesis.</p><p>This solution definition makes it clear that everytime we have a closing parenthesis we need to access the peek parenthesis in our stack and check if it is matching.</p><p>The solution we will provide will perform the following checks:</p><ol><li>If it is an open parenthesis push that in the stack.</li><li>If it is a closing parenthesis we perform the following checks:</li><li>If the stack is empty we return false because it does not find the opening parenthesis.</li><li>If the open parenthesis we found in stack does not match the closing parenthesis we return false because the string is not balanced.</li><li>Otherwise if opening and closing parenthesis match, we pop the last parenthesis.</li><li>In the end we return true only if the stack is empty because the string was balanced: for each opening parenthesis we found a closing one successfully.</li></ol><p>In the <a href="https://stackblitz.com/edit/angular-ivy-bmbned?file=src/app/stack-visualization/stack-visualization.component.ts">https://stackblitz.com/edit/angular-ivy-bmbned?file=src/app/stack-visualization/stack-visualization.component.ts</a> you can see the code and check the implementation, otherwise if you want to access only the application you could go here: <a href="https://angular-ivy-bmbned.stackblitz.io/">https://angular-ivy-bmbned.stackblitz.io</a>.</p><p><strong>Conclusions</strong></p><p>To sum up, we created a new stack using Typescript and then visualized the operations using Angular. After a detailed explanation we could put in practise the knowledge we gained from stack to solve the balanced parenthesis problem.</p><p><em>Originally published at </em><a href="https://agdev.tech/2021/03/02/stack-data-structure-in-typescript-2/"><em>http://agdev.tech</em></a><em> on March 2, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f96527693a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RxJS Explained with Vega Chart visualization]]></title>
            <link>https://agdev-tech.medium.com/rxjs-explained-with-vega-chart-visualization-b55f055bb706?source=rss-e17a654513f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b55f055bb706</guid>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[vega-visualization]]></category>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[AG Dev]]></dc:creator>
            <pubDate>Tue, 16 Feb 2021 20:14:32 GMT</pubDate>
            <atom:updated>2021-02-16T20:24:57.123Z</atom:updated>
            <content:encoded><![CDATA[<p>According to the official <a href="https://rxjs-dev.firebaseapp.com/guide/overview">documentation</a>: “RxJS is a library for composing asynchronous and event-based programs by using observable sequences.” There are lots of articles and definitions around the web related to async programming, but still challenges developers at the beginning. In my opinion RxJS is more than a library, it is a way of thinking. The demo I will create in this article will be simple to give a full picture of event based programming and will cover some easy operations.</p><p><strong>Demo Description</strong></p><p>Let’s suppose we have a chart with 10 categories of data from A -&gt; H and we also have 10 buttons corresponding to each of the chart bars. When each of the buttons is clicked we would like to update the chart. Each of the bars in the chart will show the number of times the corresponding button was clicked. This will be our end result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/0*kcSErbxjp01O_JqU" /></figure><p>In order to implement this, we need RxJS, Vega Grammar which is a declarative format for creating interactive visualizations and Angular.</p><p>First step is to install vega using</p><pre>npm install vega</pre><p>and then include inside index.html in your angular project. For this project I have been using the bar chart <a href="https://vega.github.io/vega/examples/bar-chart/">configuration</a> from Vega Examples. In the chart component there are two functions: parsing the vega configuration and then updating the data. This is the implementation:</p><pre>declare var vega: any; <br>@Component({ <br>    selector: &#39;app-chart&#39;, <br>    templateUrl: &#39;./chart.component.html&#39;, <br>    styleUrls: [&#39;./chart.component.scss&#39;] <br>}) <br>export class ChartComponent implements OnInit { <br> <br> view: View; <br> @Input() set data(values: ChartDataModel[]){ <br>    if (!this.view) { <br>        return; <br>      } <br>    this.view.remove(&#39;table&#39;, this.view.data(&#39;table&#39;)).run();   this.view.insert(&#39;table&#39;, values).run(); <br>} </pre><pre>constructor(private http: HttpClient) { } </pre><pre>ngOnInit() { <br>   this.http.get(&#39;../assets/chart-config.json&#39;)<br>  .subscribe(s =&gt; this.vegaInit(s)); } </pre><pre>public vegaInit(spec: any): any { <br>    this.view = new vega.View(vega.parse(spec)) <br>               .renderer(&#39;svg&#39;) <br>               .initialize(&#39;#chart&#39;) <br>               .width(400) <br>               .height(200) <br>               .hover()<br>             .run(); <br>    }<br> }</pre><p>Every time the user clicks one of the buttons on top, the chart should update the values and increment the corresponding bar by one. The button clicks will be a sequence of values over time. At this moment we understand that we will need a subscription to manage the values.</p><pre>this.subscription$ = fromEvent(document, &#39;click&#39;).subscribe(e =&gt; console.log(&#39;E:&#39;, e));</pre><p>From <a href="https://rxjs-dev.firebaseapp.com/guide/subscription">RxJS documentation</a> a <strong>subscription </strong>is an object that represents a disposable resource, usually the execution of an Observable. In our case, the subscription represents the documents click. Every time we click in the document we will see the message we print in the console. It is very important to unsubscribe on <strong>ngOnDestroy </strong>lifecycle hook, so that we do not cause a memory leak.</p><p>At this point we can track every click, but according to our requirements we are looking only for clicks made at one of the buttons, so we will need to manage the clicks. I have defined the list of the buttons inside the app component as below:</p><pre>buttons = [ <br>    {id: 0, title: &#39;A&#39;}, {id: 1, title: &#39;B&#39;}, <br>    {id: 2, title: &#39;C&#39;}, {id: 3, title: &#39;D&#39;}, <br>    {id: 4, title: &#39;E&#39;}, {id: 5, title: &#39;F&#39;}, <br>    {id: 6, title: &#39;G&#39;}, {id: 7, title: &#39;H&#39;} ];</pre><p>We can filter the clicks inside the subscribe function, but in order to take advantage of RxJS operators and follow the recommended guide we will need to use pipe. Pipe is useful because it separates the streaming operation from the core functionality. We are looking to emit only those events that satisfy our condition: one of A -&gt; H button click and for this reason <a href="https://rxjs-dev.firebaseapp.com/api/operators/filter">filter</a> operator is what we are looking for. Later on we will enrich the operations we will apply to our data stream.</p><pre>ngOnInit() { <br>    this.subscription$ = fromEvent(document, &#39;click&#39;) <br>        .pipe( filter(event =&gt; this.isBtnIncrementEvent(event)))<br>        .subscribe(e =&gt; console.log(&#39;E:&#39;, e)); } </pre><pre>private isBtnIncrementEvent(event: Event): boolean { <br>     const idClicked = event.target[&#39;id&#39;]; <br>     return idClicked &amp;&amp; idClicked &gt;= 0 &amp;&amp; idClicked &lt;= 7; <br>}</pre><p>Since our buttons have ids ranging from 0 to 7, by filtering the incoming clicks we now have only the clicks we need to update the chart.</p><p>Next step is to add a delay after each button click, so if the user is clicking multiple times the same button, we would like to update the chart values after 100ms that the user last clicked a button. This is just a case so that we can better demonstrate the RxJS operators. For this case we are looking at <a href="https://rxjs-dev.firebaseapp.com/api/operators/debounceTime">debounceTime</a> operator.</p><pre>ngOnInit() { <br>    this.subscription$ = fromEvent(document, &#39;click&#39;) <br>     .pipe( <br>     filter(event =&gt; this.isBtnIncrementEvent(event)),        <br>     debounceTime(100))<br>     .subscribe(e =&gt; console.log(&#39;E: &#39;, e)); }</pre><p>If you run some tests for this case, you will see that the message in the console will be printed after 100 ms after you last clicked a button.</p><p>At this point we successfully get the event when a button is clicked. Next step is to update the chart data. Inside the app component I have defined the chart data as below:</p><pre>chartData$: Subject&lt;ChartDataModel[]&gt; = new Subject([ <br>    {category: &#39;A&#39;, count: 0}, {category: &#39;B&#39;, count: 0}, <br>    {category: &#39;C&#39;, count: 0}, {category: &#39;D&#39;, count: 0}, <br>    {category: &#39;E&#39;, count: 0}, {category: &#39;F&#39;, count: 0}, <br>    {category: &#39;G&#39;, count: 0}, {category: &#39;H&#39;, count: 0} <br>]);</pre><p>I am passing this data to the chart component through binding:</p><p>From the incoming click event, we are interested only on the id of the button click, which will correspond to the index of chart data that we will increment. We are looking to project each incoming event to its target id and for this case we will need the <a href="https://rxjs-dev.firebaseapp.com/api/operators/map">map </a>operator.</p><pre>ngOnInit() { <br>    this.subscription$ = fromEvent(document, &#39;click&#39;) <br>    .pipe( <br>    filter(event =&gt; this.isBtnIncrementEvent(event)),    debounceTime(100), <br>    map((event: Event) =&gt; event.target[&#39;id&#39;]) )<br>    .subscribe(e =&gt; console.log(&#39;E: &#39;, e)); }</pre><p>If we go and check the console, we will notice that the message it will be printed is now a number, rather than an event that we saw before. Let’s say user clicked button B, now we can access id 1 which is the index of the chart data that we will have to modify.</p><p>I will use the <a href="https://rxjs-dev.firebaseapp.com/api/operators/tap">tap</a> operator to perform the side effect, which is updating the values we will pass to the chart. Tap operator will not modify the observable, so we will still see printed in the browser the index of the button that we get from the map operator.</p><pre>ngOnInit() { <br>   this.subscription$ = fromEvent(document, &#39;click&#39;) <br>   .pipe( <br>   filter(event =&gt; this.isBtnIncrementEvent(event)), <br>   debounceTime(100), <br>   map((event: Event) =&gt; event.target[&#39;id&#39;]), <br>   tap((index: number) =&gt; this.updateChartData(index)))<br>  .subscribe(e =&gt; console.log(&#39;Result: &#39;, e)); <br>} </pre><pre>private updateChartData(index: number): void { <br>   const values = this.chartData$.value; <br>  const newCount = { ...values[index], count: +values[index].count};   values[index] = newCount; this.chartData$.next([...values]); <br>}</pre><p>So this is the function that will update the chartData$ and automatically will update the chart component. If you go and test it yourself, you will see that the chart that I displayed in the beginning of this article is now correctly implemented, after each button click the correspondent bar will grow.</p><p>To sum up, I would say that when you have to deal with streams of data RxJS provides a wide range of operators, subjects, promises ect that will help you modify/update or create new streams from the incoming data in a clean and efficient way.</p><p><em>Originally published at </em><a href="https://agdev.tech/2021/02/16/rxjs-explained-with-vega-chart-visualization/"><em>http://agdev.tech</em></a><em> on February 16, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b55f055bb706" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Virtual and Infinity Scrolling]]></title>
            <link>https://agdev-tech.medium.com/angular-virtual-and-infinity-scrolling-a64cc3c4c70?source=rss-e17a654513f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/a64cc3c4c70</guid>
            <category><![CDATA[virtual-scroll]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-performance]]></category>
            <category><![CDATA[angular-cdk]]></category>
            <dc:creator><![CDATA[AG Dev]]></dc:creator>
            <pubDate>Sat, 06 Feb 2021 22:04:11 GMT</pubDate>
            <atom:updated>2021-02-07T12:58:39.006Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article I will introduce a performant solution on how to implement a list with a large amount of data. I will start with displaying a short list and next will suppose that the data set is very large. The last step will be loading this large set from the backend. In each step I will introduce the challenges and the solutions.</p><p><strong>Display a list of data</strong></p><p>Let’s suppose we have created a new component and inside the component we have items, an array with 10 elements such as: <strong><em>items = Array.from({length: 10}).map((_, i) =&gt; `Item #${i}`);</em></strong></p><p>We can easily display them by taking advantage of the <a href="https://material.angular.io/components/list/overview">Angular Material List Component</a>. Our template will be:</p><p>CSS classes container and items are defined as below:</p><pre>.container <br>{ <br>  height: 200px; <br>  width: 200px; <br>  border: 1px solid black; <br>  overflow: scroll; <br>} <br>.item { height: 50px; }</pre><p>We are doing a basic styling, each item will be 50px and the container should be 200px, in case there are more than 4 items, we will let the user scroll.</p><p>At this point we can see the list rendered in the browser and the solution is fast.</p><p><strong>Display a large list of data</strong></p><p>Let’s suppose that our items array will have 100.000 elements and change the items inside the component like this: <strong><em>items = Array.from({length: 100000}).map((_, i) =&gt; `Item #${i}`);</em></strong></p><p>By using the same template as before, if we check the browser the solution still works and all the elements are rendered in the browser. That is what we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_iE-b66h-ppFAs1i" /></figure><p>So the solution that seemed perfect for the first requirement, now it comes with performance issues. We are loading 100.000 elements and the user can only see 4 at a time, so our first thought would be why don’t we just load the elements that the user is seeing and probably a couple more. By using this logic, users will not notice any latency when scrolling and the biggest advantage is that we don’t need to render all these elements.</p><p>That’s when Virtual Scrolling comes into hand. According to <a href="https://material.angular.io/cdk/scrolling/overview">Angular Scrolling Documentati</a>: <em>“The &lt;cdk-virtual-scroll-viewport&gt; displays large lists of elements performantly by only rendering the items that fit on-screen. “</em></p><p>Let’s add ScrollingModule and take advantage of the virtual scrolling.<em> (In order to use ScrollingModule you should install </em><strong><em>@angular/cdk</em></strong><em> in your project).</em></p><p>We will replace <em>mat-list</em> with the<strong><em> cdk-virtual-scroll-viewport</em></strong> and <em>*ngFor</em> with <strong><em>*cdkVirtualFor</em></strong>. Now the template will look like this:</p><p>The viewport can be customized with different scroll strategies, you can use this array or a custom data source, but I will show just the benefits of virtual scroll and how to do a simple implementation. For more information please refer to the official documentation. This is the result in browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/0*Ro31YkDnk8SRPi56" /></figure><p>There are only 12 elements rendered and if you try it yourself you will see as you scroll down the rendered elements will change, so it will be a much better user experience.</p><p><strong>Display a list of data fetched in backend</strong></p><p>Now let’s suppose we will load the data from the backend. Even though we are now rendering a small number of items in the browser, if we have to fetch 100.000 items it will take a long time. So let’s suppose we can ask to load only a partial amount of data from the backend, pagination logic. We need to send a request to load the items from a specific index.</p><p>For this example, I will create a simple function that will return me the data from a starting index. It will be simple for you to update it in a real case scenario. We will use the <strong>scrolledIndexChanged </strong>event inside the viewport to get the scroll event and will update the template as below:</p><p>Now let me first show you the update component and I will get in details what each part is responsible for:</p><pre>export class VirtualScrollComponent { <br> items = []; <br> pageSize = 10; <br> fetchedRanges = new Set&lt;number&gt;(); @ViewChild(CdkVirtualScrollViewport) virtualScroll: CdkVirtualScrollViewport; </pre><pre>constructor() { } </pre><pre>onScroll(): void { <br> const renderedRange = this.virtualScroll.getRenderedRange(); <br> const end = renderedRange.end; <br> const total = this.items.length; <br> const nextRange = end + 1; <br> if (end == total &amp;&amp; !this.fetchedRanges.has(nextRange)) { <br>   this.items = [...this.items, ...this.loadData(nextRange,       this.pageSize)]; <br> this.fetchedRanges.add(nextRange); <br> } <br>} <br>private loadData(start: number, size: number): string[] <br>{ <br>  if (start === 100000) { <br>      return []; <br>   } <br>return this.range(start, size); <br>} </pre><pre>private range(start: number, size: number): string[] { <br> return [...Array(size).keys()].map(i =&gt; `Item #${i + start}`); } <br>}</pre><p>When the user scrolls, we will check if the rendered range is the last loaded range. In order to avoid multiple calls to our “backend” function we will use a set <strong>fetchedRanges</strong>, where we will keep all the loaded ranges. Let’s suppose the user is scrolling in index 5, we go and check that this is the last loaded range and ask to load the next range. Meanwhile, when the next range is loading, if the user continues to scroll and if we don’t save in the set that we asked for range 2, it will go and ask the backend again to get the next range. The set will make more sense when you apply it in a real application.</p><p>The loadData function is returning a piece of data and doing a simple check if the index we are asking is 100.000 and if so will return an empty array supposing that we loaded all the data. Once we return the empty array, we will not execute the load data function, because the set will have the index 100.000.</p><p><strong>Conclusions</strong></p><p>If you are dealing with large data sets virtual scrolling will help you render only a small amount of items and it manages to update the view when the user scrolls. If you are getting this large amount of data from the backend Infinite Scrolling will allow you to do so, without affecting the user experience.</p><p><em>Originally published at </em><a href="http://agdev.tech/2021/02/06/angular-virtual-and-infinity-scrolling/"><em>http://agdev.tech</em></a><em> on February 6, 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a64cc3c4c70" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ANGULAR DEPENDENCY INJECTION EXPLAINED]]></title>
            <link>https://agdev-tech.medium.com/angular-dependency-injection-explained-a98c011b2a2b?source=rss-e17a654513f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/a98c011b2a2b</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[dependency-management]]></category>
            <category><![CDATA[inversion-of-control]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[AG Dev]]></dc:creator>
            <pubDate>Sun, 31 Jan 2021 08:00:49 GMT</pubDate>
            <atom:updated>2021-01-31T08:20:18.760Z</atom:updated>
            <content:encoded><![CDATA[<p>When I first started programming dependency injection and all the concepts related to it seemed to be a bit abstract for me. I could still create services and inject them, but still there seemed to be a gap in my mind on how this implementation seemed to work.</p><p>In this article, first I will explain what are the issues DI had to solve by starting with an example where we DI is not used. Step by step I will introduce the benefits of using DI as a coding pattern and how it makes programming easier.</p><ul><li><strong>Code without DI</strong></li></ul><p>Let’s start with a simple example, we have a class called Laptop which has two properties: RAM and CPU. It is quite simple te declare it as below:</p><pre>export class Cpu {<br> <br>    constructor() {}<br>}</pre><pre>export class Ram {<br> <br>    constructor() {}<br>}</pre><pre>export class Laptop {<br>    cpu: Cpu;<br>    ram: Ram;<br>    <br>    constructor() {<br>        this.cpu = new Cpu();<br>        this.ram = new Ram();<br>    }<br> <br>}</pre><p>At this point we can create a new instance of laptop pretty easy: <strong>const laptop: Laptop = new Laptop();</strong></p><p>Now let’s change a bit the Ram and Cpu classes, supposing that Ram needs a size and a unit to be initiated and Cpu needs a model.</p><pre>export class Ram {<br>    size: number;<br>    unit: string;<br> <br>    constructor(size: number, unit: string) {<br>        this.size = size;<br>        this.unit = unit;<br>    }<br>}</pre><pre>export class Cpu {<br>    model: string;<br> <br>    constructor(model: string) {<br>        this.model = model;<br>    }<br>}</pre><p>As we can see we need to make changes on laptop constructor, because when creating a new laptop we will need to provide cpu model, ram size and ram unit. <strong>const laptop: Laptop = new Laptop(‘Intel’, 8, ‘GB’);</strong></p><pre>export class Laptop {<br>    cpu: Cpu;<br>    ram: Ram;<br>    <br>    constructor(cpuModel: string, ramSize: number, ramUnit: string) {<br>        this.cpu = new Cpu(cpuModel);<br>        this.ram = new Ram(ramSize, ramUnit);<br>    }<br>}</pre><p>Now as we can see, we need three parameters in this simple example. Imagine if we had to really define a new laptop the amount of parameters we should provide and hard it will be at some point to manage it all. Another drawback is that once we change the parameters needed to initialize Cpu for example, we will need to modify the Laptop too. If we add a generation parameter to Cpu, we will need to update the laptop as well. It will be hard to manage such code. On the other hand it would be impossible to test it. This background will make it easy for us now to understand a bit more dependency injection.</p><ul><li><strong>DI as a design pattern</strong></li></ul><p>According to Angular: “<a href="https://angular.io/guide/dependency-injection"><strong><em>Dependency Injection is a coding pattern in which a class receives its dependencies from external sources rather than creating it itself.”</em></strong> </a>What this definition is basically saying is that since a laptop has a dependency on cpu and ram, it will get these dependencies provided to it. Which means that laptop class will be as follows:</p><pre>export class Laptop {<br>    cpu: Cpu;<br>    ram: Ram;<br>    <br>    constructor(cpu: Cpu, ram: Ram) {<br>        this.cpu = cpu;<br>        this.ram = ram;<br>    }<br>}</pre><p>To create a new laptop we will need to first create an instance of Cpu and Ram as below:</p><pre>const cpu: Cpu = new Cpu(&#39;Intel&#39;);       <br>const ram: Ram = new Ram(8,&#39;GB&#39;);     <br>const laptop: Laptop  = new Laptop(cpu, ram);</pre><p>By providing the dependencies: cpu and ram to laptop we solved the problem we noticed before. So if we add the generation to cpu the laptop does not need to change, it will still just get cpu as a parameter.</p><pre>const cpu: Cpu = new Cpu(&#39;Intel&#39;, &#39;i9-9900K&#39;);<br>const ram: Ram = new Ram(8,&#39;GB&#39;);<br>const laptop: Laptop  = new Laptop(cpu, ram);</pre><p>Now we can see the advantages of providing the dependencies externally. Supposing that laptop will need cpu, ram, keyboard..ect still we will have issues because we will need to manually create a ton of dependencies manually. Furthermore in the application it might be necessary to create lots of new instances and we will just need to copy paste the code which is definitely not a good practise.</p><ul><li><strong>DI as a framework</strong></li></ul><p>At this point we could create the new laptop instance by providing the dependencies externally ourselves. Now we will take it one step further and will allow Angular to create these dependencies when needed and we will just provide the default values which can be customized according to our needs. Let’s start first with Cpu:</p><pre>@Injectable()<br>export class Cpu {<br> model: string;<br> generation: string;<br> <br> constructor(@Inject(&#39;model&#39;) model: string, @Inject(&#39;generation&#39;) generation:  string)   {<br>        this.model = model;<br>        this.generation = generation;<br> }<br>}</pre><p>By using <strong>@Inject()</strong> we are telling Angular that Cpu has a dependency on model and whenever Cpu class is used Angular DI Framework will provide the dependency to us. We will do the same thing for Ram by injecting the parameters as in Cpu. Now we need to provide them and for now I will just provide them inside app module providers as below and later I will get in more details:</p><pre>providers: [   <br>      Cpu,<br>      Ram,<br>      {provide: &#39;model&#39;, useValue: &#39;Intel&#39;}, <br>      {provide: &#39;generation&#39;, useValue: &#39;i9-9900K&#39;},<br>      {provide: &#39;size&#39;, useValue: 8},<br>      {provide: &#39;unit&#39;, useValue: &#39;GB&#39;}      <br>  ],</pre><p>Now it’s very easy to create a new laptop:</p><pre>constructor(private cpu: Cpu, private ram: Ram) {<br>      this.createLaptop();<br>  }<br> <br>  createLaptop(): void {<br>      const laptop: Laptop  = new Laptop(this.cpu, this.ram);<br>      console.log(&#39;Laptop: &#39;, laptop);<br>  }</pre><p>So we are injecting Cpu and Ram and then we are creating a new instance of laptop. And if we check in the browser this is the instance we created:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/0*weIEZEPDCE7JWb8O" /></figure><p>So Angular DI Framework has automatically created a new instance of cpu and ram using the values we provided successfully.</p><p>Let’s consider the case where we have two modules and when we create a new laptop each of the modules create a different laptop such as Module A: Intel Laptop and Module B: AMD Laptop.</p><p>In this case we need to tell Angular that when each of the modules is initiated it should provide different values for model, generation, ram size and unit. These are the values that we inject in CPU and RAM.</p><p>In Module A this will be the providers:</p><pre>providers: [<br>        Ram, Cpu,<br>        {provide: &#39;model&#39;, useValue: &#39;AMD&#39;}, <br>        {provide: &#39;generation&#39;, useValue: &#39;Radeon&#39;},<br>        {provide: &#39;size&#39;, useValue: 32},<br>        {provide: &#39;unit&#39;, useValue: &#39;GB&#39;}    <br>    <br>    ]</pre><p>And in module B:</p><pre>providers: [<br>        Ram, Cpu,<br>        {provide: &#39;model&#39;, useValue: &#39;Intel&#39;}, <br>        {provide: &#39;generation&#39;, useValue: &#39;i9-9900K&#39;},<br>        {provide: &#39;size&#39;, useValue: 16},<br>        {provide: &#39;unit&#39;, useValue: &#39;GB&#39;}   <br>    ]</pre><p>If we create a laptop inside each of the modules, when we load them in the browser we will see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/0*NAAUnDz6Liveonw-" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/0*Qy3l0GijpwHJ94P-" /></figure><p>So at this point we have successfully injected Ram and Cpu in each of the components and provided different values that Angular DI injected at our A component and B Component.</p><ul><li><strong>Conclusions</strong></li></ul><p>Dependency Injection design pattern is when you provide the instance dependencies externally. Dependency Injection Framework is when you define the dependencies and Angular automatically provides them to components. When speaking of Dependency Injection it is most related to services, but in the example that I chose I hope I made it clear that the concept is quite straightforward: One class has a dependency which can be a string/number/boolean parameter, service or another class and by properly configuring it Angular Injector will provide that when it is needed.</p><p>In the next article I will get more in depth regarding the services, how hierarchical injector works and different options to configure dependencies such as useClass, useValue, useExisting and so on.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a98c011b2a2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step by step guide: Application using NestJs and Angular]]></title>
            <link>https://agdev-tech.medium.com/step-by-step-guide-application-using-nestjs-and-angular-fc4a91484e3e?source=rss-e17a654513f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc4a91484e3e</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[nestjs-tutorial]]></category>
            <dc:creator><![CDATA[AG Dev]]></dc:creator>
            <pubDate>Fri, 15 Jan 2021 16:23:50 GMT</pubDate>
            <atom:updated>2021-01-22T08:07:49.881Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Step by step guide: Application using NestJs and Angular</strong></p><p>Just a few days before Christmas I came along with NestJs framework. Always wanted to give a try to NodeJs development, but the idea of a javascript backend seemed to keep me away.</p><p>NestJs is a framework for building Node.js server side applications and supports Typescript. Since almost all my experience is with Angular and NestJs provides an out-of-the box application architecture heavily inspired by Angular, it seemed like all the boxes were checked and I had to give it a try. For more information please visit <a href="https://docs.nestjs.com/">NestJs Official Documentation</a>.</p><p>In this post I will show you how to create a simple application with Angular Front End, NestJs Back End and Postgres Database. To integrate with database Nest uses TypeORM and we will need to specify postgres when installing TypeORM.</p><p><strong>Application Description</strong></p><p>I will create a demo application that will manage the user budget. The user can create, update, view and delete expenses and incomes. For each expense there will be an expense category and I will set up first the expense category for this article.</p><p><strong>Server Side Application with NestJs</strong></p><p>First step is to set up and create the application using the following commands:</p><ol><li>npm i -g @nestjs/cli</li><li>nest new budget-be</li><li>npm install — save @nestjs/typeoprm typeorm postgres</li></ol><p>At this point we are ready to start working with the server side application. When creating the server side application by default it is created an App Module, App Controller and App Service.</p><p><strong>Connecting to the database</strong></p><p>I have created the budget-management database in Postgres. In App Module we will need to set up the connection to the database by specifying it inside TypeOrmModule in the import.</p><pre>TypeOrmModule.forRoot({<br>       type: &quot;postgres&quot;,<br>       host: &quot;localhost&quot;,<br>       port: 5432,<br>       username: &quot;postgres&quot;,<br>       password: &quot;root&quot;,<br>       database: &quot;budget-management&quot;,<br>       entities: [ExpenseCategory],<br>       synchronize: true<br>})</pre><p>Inside the TypeOrmModule import I have specified the host, username, database name and password according to my definitions. At this point we are ready to start implementing the Expense Category Module.</p><p><strong>Setup Expense Category Module</strong></p><p>Here will show you steps to create Expense Category Module that will be responsible for all the requests coming to ‘expense-category’ from the front end.</p><ol><li><strong>Expense Category Dto</strong></li></ol><p>First I will create the Expense Category DTO (Data Transfer Object) which determines how the data will be sent over the network. We will use it inside the controller later. For this example it will be a very simple object containing only an id and a category. The implementation is done as follows:</p><pre>export class ExpenseCategoryDto {<br>       readonly id: number;<br>       readonly category: string;<br>}</pre><p><strong>2. Expense Category Entity</strong></p><p>Entity class marked with @Entity decorator corresponds to an entity in the database. The expense category entity will be:</p><pre><strong>@Entity</strong>()<br>export class <strong>ExpenseCategory</strong> {</pre><pre>       @PrimaryGeneratedColumn()<br>       id: number;</pre><pre>      @Column()<br>      category: string;</pre><pre>}</pre><p>In order to use the entity we should specify it inside the TypeOrmModule.</p><p><strong>3. Expense Category Controller</strong></p><p>Controllers are responsible to receive requests and return a response to the client. It is the routing mechanism that decides which controller should handle the incoming request. My application will display a list of expense categories that the user can update, delete or create a new one. So I will need to manage in my controller all these types of requests. Here is the controller I implemented:</p><pre><strong>@Controller(&#39;expense-category&#39;)</strong><br>export class <strong>ExpenseCategoryController </strong>{</pre><pre>constructor(private expenseCategoryService: ExpenseCategoryService){}</pre><pre>@Get()<br>getExpenseCategories() {<br>    return this.expenseCategoryService.find();<br>}</pre><pre>@Post()<br>create(@Body() expenseCategory: ExpenseCategoryDto) {<br>    return this.expenseCategoryService.create(expenseCategory);<br>}</pre><pre>@Get(&#39;:id&#39;)<br>findOne(@Param(&#39;id&#39;) id: string) {<br>     return this.expenseCategoryService.findOne(id);<br>}</pre><pre>@Put()<br>@ApiBody({ type: ExpenseCategoryDto })<br>update(@Body() expenseCategory: ExpenseCategoryDto) {<br>     return this.expenseCategoryService.update(expenseCategory);<br>}</pre><pre>@Delete(&#39;:id&#39;)<br>remove(@Param(&#39;id&#39;) id: number) {<br>     this.expenseCategoryService.remove(id);<br>}</pre><pre>}</pre><p><strong>4. Expense Category Repository</strong></p><p>TypeORM supports the repository design pattern, for this reason the Expense Category Entity will have its own repository. To implement a custom repository we need to extend Repository from typeorm and it is marked with @EntityRepository decorator. The implementation is as below. I have implemented this just to try it, but even the default repository is fine for this case.</p><pre><strong>@EntityRepository(ExpenseCategory)</strong><br>export class <strong>ExpenseCategoryRepository </strong>extends  Repository&lt;ExpenseCategory&gt; {</pre><pre>createExpenseCategory = async (expenseCategoryDto: ExpenseCategoryDto) =&gt; {<br>     return await this.save(expenseCategoryDto);<br>     };<br>}</pre><p><strong>5. Expense Category Service</strong></p><p>Dependency Injection works the same as Angular. I will define a service using @Injectable decorator and will declare it under Providers in Expense Category Module. Here I will implement all the methods to create, get, find, update and delete that I have used inside the controller.</p><pre><strong>@Injectable()</strong><br>export class <strong>ExpenseCategoryService </strong>{</pre><pre>constructor(<br>        @InjectRepository(ExpenseCategoryRepository) private    readonly expenseCategoryRepository: ExpenseCategoryRepository){}</pre><pre>find() {<br>    return this.expenseCategoryRepository.find();<br>}</pre><pre>create(expenseCategory: ExpenseCategoryDto) {<br>    return this.expenseCategoryRepository.insert(expenseCategory);<br>}</pre><pre>findOne(id: string) {<br>    return this.expenseCategoryRepository.findOne(id);<br>}</pre><pre>update(expenseCategory: ExpenseCategoryDto) {<br>    return this.expenseCategoryRepository.save(expenseCategory);<br>}</pre><pre>remove(id: number) {<br>    this.expenseCategoryRepository.delete(id);<br> }<br>}</pre><p><strong>6. Expense Category Module</strong></p><p>At this point we have set up the expense category entity, controller, service, repository and dto. We will include this in the Expense Category Module which later will be imported in the App Module and we can consider the server side implementation finished.</p><pre>@Module({<br>   imports: [<br>     TypeOrmModule.forFeature(<br>       [ExpenseCategory, ExpenseCategoryRepository]<br>)],<br>controllers: [ExpenseCategoryController],<br>providers: [ExpenseCategoryService]<br>})</pre><pre>export class <strong>ExpenseCategoryModule </strong>{}</pre><p><strong>Front End Application with Angular</strong></p><p>After setting up the server side application, I will create a new Angular Application that will connect to NestJs Application to display and modify expense categories. I will not get in deep details regarding the Angular implementation, but rather give you a general implementation.</p><p>By executing:</p><ol><li><strong>ng new budget-fe</strong></li><li><strong>ng g c expense-category</strong></li></ol><p>will create the budget management application and the expense category component. In order to connect to server side I will configure proxy.conf.json as below:</p><pre>{<br>  &quot;/api/*&quot;: {<br>       &quot;target&quot;: &quot;http://localhost:3000&quot;,<br>       &quot;secure&quot;: false,<br>       &quot;logLevel&quot;: &quot;debug&quot;,<br>       &quot;changeOrigin&quot;: true,<br>       &quot;pathRewrite&quot;: {<br>             &quot;^/api&quot;: &quot;&quot;<br>        }<br>    }<br>}</pre><p><strong>Implementing CRUD in Angular for Expense Category.</strong></p><p>First I will implement the service that will handle all the requests as below:</p><p>After implementing the service will update the expense-category-component to get the data and add some actions to the ui such as: create, modify and delete.</p><pre><strong>@Injectable()</strong><br>export class <strong>ExpenseCategoryService </strong>{<br>    static URL = &#39;/api/expense-category&#39;;</pre><pre>constructor(public http: HttpClient){}</pre><pre>getCategories(): Observable&lt;ExpenseCategoryModel[]&gt; {<br>       return this.http.get&lt;ExpenseCategoryModel[]&gt;<br>               ExpenseCategoryService.URL);<br>}</pre><pre>createCategory(category: ExpenseCategoryModel) {<br>    return this.http.post(ExpenseCategoryService.URL, category);<br>}</pre><pre>modifyCategory(category: ExpenseCategoryModel): Observable&lt;ExpenseCategoryModel&gt; { <br>     return this.http.put&lt;ExpenseCategoryModel&gt;            ExpenseCategoryService.URL, category);<br>}</pre><pre>deleteCategory(id: number): Observable&lt;any&gt; {<br>  return this.http.delete(ExpenseCategoryService.URL + `/${id}`);<br>}<br>}</pre><p>The template for this example will be a list of items displaying the id and name of the category.</p><pre>&lt;button mat-mini-fab (click)=&quot;add()&quot;&gt;<br>  &lt;mat-icon&gt;add&lt;/mat-icon&gt;<br>&lt;/button&gt;</pre><pre>&lt;mat-list *ngIf=&quot;expenses$ | async as expenses&quot;&gt;<br>     &lt;mat-list-item *ngFor=&quot;let expense of expenses&quot;&gt;<br>           &lt;div mat-line&gt;{{expense.id}}<br>             &lt;button mat-mini-fab (click)=&quot;modify(expense.id)&quot; &gt;<br>                 &lt;mat-icon&gt;edit&lt;/mat-icon&gt;<br>             &lt;/button&gt;<br>            &lt;button mat-mini-fab (click)=&quot;delete(expense.id)&quot;&gt;<br>                &lt;mat-icon&gt;delete&lt;/mat-icon&gt;<br>            &lt;/button&gt;<br>         &lt;/div&gt;<br>         &lt;div mat-line&gt;{{expense.category}} &lt;/div&gt;<br>   &lt;/mat-list-item&gt;<br>&lt;/mat-list&gt;</pre><p>Component definition will be:</p><pre><strong>@Component</strong>({<br>    selector: &#39;app-expense-category&#39;,<br>    templateUrl: &#39;./expense-category.component.html&#39;,<br>    styleUrls: [&#39;./expense-category.component.scss&#39;]<br>})</pre><pre>export class <strong>ExpenseCategoryComponent </strong>implements OnInit {<br> <br>expenses$: Observable&lt;any[]&gt;;</pre><pre>constructor(private service: ExpenseCategoryService) { }</pre><pre>ngOnInit(): void {<br>     this.getCategories();<br>}</pre><pre>getCategories = () =&gt; {<br>    this.expenses$ = this.service.getCategories();<br>}</pre><pre>add(): void {<br>  const newCategory = {id: null, category: &#39;New Category&#39;};<br>  this.service.createCategory(newCategory);<br>}</pre><pre>modify(id: number) {<br>   const updatedCategory  = {id, category: &#39;Modified Category&#39;};<br>   this.service.modifyCategory(updatedCategory);<br>}</pre><pre>delete(id: number) {<br>   this.service.deleteCategory(id).subscribe(this.getCategories);<br>  }<br>}</pre><p>In the component I am injecting the service in order to get, update and delete expense categories. As I mentioned before the front end is a simple implementation just to see that the applications are connecting with each other and I have correctly implemented the server side.</p><p><strong>Conclusions</strong></p><p>NestJs is in my opinion a great solution for the Angular Developers (like me) to start coding in NodeJs environment as it is heavily based on Angular. Creating a simple application, both server side and front end was easy and quite interesting for me. I will continue to work and experiment in NestJs and will give you more updates. I would highly recommend giving it a try because as they say: <em>“The proof of the pudding is in the eating”</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc4a91484e3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tips to organize better Reactive Forms in Angular]]></title>
            <link>https://agdev-tech.medium.com/tips-to-organize-better-reactive-forms-in-angular-abbcc9c58cc8?source=rss-e17a654513f4------2</link>
            <guid isPermaLink="false">https://medium.com/p/abbcc9c58cc8</guid>
            <category><![CDATA[angular-reactive-form]]></category>
            <category><![CDATA[reactive-forms]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[AG Dev]]></dc:creator>
            <pubDate>Tue, 12 Jan 2021 10:29:02 GMT</pubDate>
            <atom:updated>2021-01-12T10:29:02.960Z</atom:updated>
            <content:encoded><![CDATA[<p>When building applications at some point you will need the user input, either a value or a whole set of data. That’s when forms come into play.</p><p>Angular provides two types of forms: Template Driven and Reactive Forms. Depending on your requirements you will have to choose between the two. Template driven forms are easier to set up, but less scalable. If you have an easy form such as login where you will have only two inputs it might be a good idea to use template driven forms. Reactive forms are more customizable and scalable. If you have lots of data you are expecting from the user you need to go with reactive forms. I will list below some tips and tricks how to manage large forms.</p><ol><li><strong>Group your form controls</strong></li></ol><p>When creating a form you might have a large number of form controls. My advice is to group them. Each of the groups will correspond to a component. Advantages of grouping form controls are scalability and reusability. Now I will show you an easy example to demonstrate why it is a good practise to group the form controls.</p><p>Let’s suppose you are creating a poll to ask students some questions. This will be managed by a form and we’ll send the request to backend to save the results. We will ask the students general information, subjects related information and if the student is a freshman we will ask them a couple more questions.</p><pre>getPollFormGroup(): FormGroup {     <br>       return new FormGroup({         <br>       firstName: new FormControl([Validators.required]),  <br>       lastName: new FormControl([Validators.required]),                                                                                         <br>       isFreshman: new FormControl(true),<br>       freshmanForm: this.getFreshmanFormGroup(),       <br>       mathematicsForm: this.getSubjectFormGroup(),          <br>       programmingForm: this.getSubjectFormGroup(),<br>       englishForm: this.getSubjectFormGroup()     <br>    })   <br>}   </pre><pre>getSubjectFormGroup(): FormGroup {       <br>      return new FormGroup({                                        <br>      subjectRating: new FormControl([Validators.required]),      <br>      professorRating: new FormControl([Validators.required]),                    <br>      difficultiesUnderstanding: new FormControl(), <br>      opinion: new FormControl()     <br>    })   <br>}   </pre><pre>getFreshmanFormGroup(): FormGroup {      <br>      return new FormGroup({        <br>      gapsSubjects: new FormControl([Validators.required]),                  <br>      changes: new FormControl([Validators.required]),      <br>      improvements: new FormControl([Validators.required])    <br>  })   <br>}</pre><p>This will be our initial component and we will modify it as we proceed. As we see in the constructor we are creating a new form group using getPollFormGroup function. We need a form control, which we will later visualize as a checkbox to manage the form if the student is a freshman. In that case we will ask for some more information such as if they have gaps in understanding the subjects, things they do not like and would change and improvements on the current curricula. On the other side we are asking for information for three subjects: mathematics, informatics and english.</p><p>By grouping our form controls related to the subjects the form is more scalable and reusable. Without grouping the form controls our getPollFormGroup would look like this:</p><pre>getNonGroupedPollFormGroup(): FormGroup {     <br>      return new FormGroup({         <br>      firstName: new FormControl([Validators.required]),          <br>      lastName: new FormControl([Validators.required]),<br>      isFirstYear: new FormControl(true),         <br>      freshmanForm: this.getFreshmanFormGroup(),       <br>      mathematicsForm: this.getSubjectFormGroup(), <br>      mathematicsRating: new FormControl([Validators.required]),<br>      mathematicsProfessorRating: new    FormControl([Validators.required]),  <br>     mathematicsDifficultiesUnderstanding: new FormControl(), <br>     mathematicsOpinion: new FormControl(),      <br>     programmingRating: new FormControl([Validators.required]),  <br>     programmingRatingProfessorRating: new FormControl([Validators.required]),<br>    programmingRatingDifficultiesUnderstanding: new FormControl(), <br>    programmingRatingOpinion: new FormControl(),  <br>    englishRating: new FormControl([Validators.required]),<br>    englishProfessorRating: new FormControl([Validators.required]),       <br>    englishDifficultiesUnderstanding: new FormControl(), <br>    englishOpinion: new FormControl()     <br>})   <br>}</pre><p>The definition is longer and if later on we would like to add more subjects it would become unmanageable. The grouped form controls on the other hand is very scalable, we would just add new subjects polls quite easy such as:</p><p><strong>geographyForm: this.getSubjectFormGroup()</strong></p><p><strong>2. Use smart and dumb components .</strong></p><p>We need a smart component that will manage validation, error handling and a dumb component which will be responsible to only visualize form controls. Subject Form will expect as input a form group and then will display the form controls. Splitting the logic from the visualisation will make it easier to manage the code when you need to make changes or add new form controls. Dumb components that only visualize data are easy to reuse as you can see below. Grouping form controls made it easier to reuse the subject form component.</p><pre>&lt;app-subject-form         <br>     [form]=&quot;form.get(&#39;programmingForm&#39;)&quot;&gt;<br>&lt;/app-subject-form&gt;    </pre><pre>&lt;app-subject-form         <br>     [form]=&quot;form.get(&#39;englishForm&#39;)&quot;&gt;<br>&lt;/app-subject-form&gt;</pre><p>3. <strong>Subscribe to value changes.</strong></p><p>When using the parent-child component structure where parent is the smart component and children are dumb components, if we want to do a specific action when a value changes we can subscribe to Event Emitters. Let’s suppose we want to show the user a message every time the rating of a subject changes we can subscribe and in the smart component we manage the function. From my experience instead of using @OutputEmitter in child component and subscribing to parent component we can use value changes such as:</p><pre>ngOnInit() {   <br>     this.form.get(&#39;programmingForm.subjectRating&#39;).valueChanges.   <br>               pipe(filter(v =&gt; v != null)) <br>              .subscribe(this.programmingRatingInterceptor);     <br>}   </pre><pre>programmingRatingInterceptor = (rating: number): void =&gt; {      <br>     if (rating &lt; 3) {         <br>        console.log(&#39;We are sorry you share this opinion!&#39;);       <br>    }   <br>}</pre><p>So every time the rating inside the programming form changes we will print in console this message. It’s easier and more straightforward than subscribing to event emitters. Another advantage is that you can use rxjs operators to filter or manipulate data upon requests.</p><p>As you can see grouping your form controls and then creating one smart component to manage the logic, validation and custom operations and some dumb components to visualise the form will make it easier to manage and scale.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abbcc9c58cc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>