<?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 Daniel Haile on Medium]]></title>
        <description><![CDATA[Stories by Daniel Haile on Medium]]></description>
        <link>https://medium.com/@daniel-haile?source=rss-c07a36e3119------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*3_Yy3lLOO84wtFcT</url>
            <title>Stories by Daniel Haile on Medium</title>
            <link>https://medium.com/@daniel-haile?source=rss-c07a36e3119------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 23:37:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@daniel-haile/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[How can you prevent XSS attacks in an Angular application?]]></title>
            <link>https://medium.com/@daniel-haile/how-can-you-prevent-xss-attacks-in-an-angular-application-0387cec5ec0a?source=rss-c07a36e3119------2</link>
            <guid isPermaLink="false">https://medium.com/p/0387cec5ec0a</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Daniel Haile]]></dc:creator>
            <pubDate>Tue, 09 Jan 2024 19:35:34 GMT</pubDate>
            <atom:updated>2024-01-11T22:20:42.833Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>How can you prevent XSS attacks in an Angular application?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l7c28MhOm6ex7soaCf0e_Q.png" /><figcaption><strong>prevent XSS attacks in an Angular application</strong></figcaption></figure><h3>1. Import DomSanitizer and SafeHtml:</h3><pre>import { Component } from &#39;@angular/core&#39;;<br>import { DomSanitizer, SafeHtml } from &#39;@angular/platform-browser&#39;;</pre><h3>2. Create an Angular Component:</h3><pre>@Component({<br>  selector: &#39;app-root&#39;,<br>  template: `<br>    &lt;div [innerHTML]=&quot;sanitizedHtml&quot;&gt;&lt;/div&gt;<br>  `<br>})<br>export class AppComponent {<br>  userGeneratedHtml: string = &#39;&lt;script&gt;alert(&quot;XSS attack!&quot;)&lt;/script&gt;&#39;;<br>  sanitizedHtml: SafeHtml;<br><br>  constructor(private sanitizer: DomSanitizer) {<br>    this.sanitizedHtml = this.sanitizer.bypassSecurityTrustHtml(this.userGeneratedHtml);<br>  }<br>}</pre><h3>3. Use bypassSecurityTrustHtml Method:</h3><pre>this.sanitizedHtml = this.sanitizer.bypassSecurityTrustHtml(this.userGeneratedHtml);</pre><h3>4. Bind to [innerHTML] Property:</h3><pre>&lt;div [innerHTML]=&quot;sanitizedHtml&quot;&gt;&lt;/div&gt;</pre><h3>Summary:</h3><ul><li>Import DomSanitizer and SafeHtml.</li><li>Create a component property for user-generated HTML content.</li><li>Use this.sanitizer.bypassSecurityTrustHtml to sanitize the HTML content.</li><li>Bind the sanitized content using [innerHTML] property in the template.</li></ul><p>Thank you for reading!</p><p>Happy Coding!!</p><p>Follow me on <a href="https://medium.com/@daniel-haile"><strong>Medium</strong></a> for more interesting articles!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0387cec5ec0a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to pass data from Child to Parent Component in React.js?]]></title>
            <link>https://medium.com/@daniel-haile/how-to-pass-data-from-child-to-parent-component-in-react-js-14cee5f3b6f9?source=rss-c07a36e3119------2</link>
            <guid isPermaLink="false">https://medium.com/p/14cee5f3b6f9</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Daniel Haile]]></dc:creator>
            <pubDate>Sun, 24 Dec 2023 06:55:15 GMT</pubDate>
            <atom:updated>2023-12-24T06:55:15.091Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tAmYx1PGEmWi_FmVZthkug.jpeg" /><figcaption>React most asked Interview question</figcaption></figure><p>In React, data is typically passed from a child component to a parent component through the use of callback functions. Here’s a basic example of how you can achieve this:</p><h3>Child Component (ChildComponent.js):</h3><pre>import React, { useState } from &#39;react&#39;;<br><br>const ChildComponent = ({ onDataSend }) =&gt; {<br>  const [dataToSend, setDataToSend] = useState(&#39;&#39;);<br><br>  const handleSendData = () =&gt; {<br>    // Do any necessary processing with dataToSend<br>    const processedData = dataToSend.toUpperCase();<br><br>    // Call the callback function provided by the parent<br>    onDataSend(processedData);<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        value={dataToSend}<br>        onChange={(e) =&gt; setDataToSend(e.target.value)}<br>      /&gt;<br>      &lt;button onClick={handleSendData}&gt;Send Data to Parent&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default ChildComponent;</pre><h3>Parent Component (ParentComponent.js):</h3><pre>import React, { useState } from &#39;react&#39;;<br>import ChildComponent from &#39;./ChildComponent&#39;;<br><br>const ParentComponent = () =&gt; {<br>  const [receivedData, setReceivedData] = useState(&#39;&#39;);<br><br>  // Callback function to receive data from the child<br>  const handleDataReceive = (data) =&gt; {<br>    setReceivedData(data);<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Data Received from Child: {receivedData}&lt;/h1&gt;<br>      &lt;ChildComponent onDataSend={handleDataReceive} /&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default ParentComponent;</pre><p>In this example:</p><ol><li>The ChildComponent maintains its own state (dataToSend) and updates it as the user interacts with the input field.</li><li>When the “Send Data to Parent” button is clicked, the handleSendData function is called. This function processes the data (you can perform any necessary operations here) and then invokes the onDataSend callback passed from the parent with the processed data.</li><li>The ParentComponent has its own state (receivedData) that gets updated when the callback function (handleDataReceive) is called. The parent renders the ChildComponent and passes the callback function (onDataSend) to it as a prop.</li></ol><p>This pattern allows the child component to communicate with its parent by invoking the callback function provided by the parent, passing data in the process.</p><p>Thank you for reading!!</p><p>Follow me on <a href="https://medium.com/@daniel-haile"><strong><em>medium</em></strong></a> for more articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14cee5f3b6f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Angular Life Cycle?]]></title>
            <link>https://medium.com/@daniel-haile/why-angular-life-cycle-e14469c96d24?source=rss-c07a36e3119------2</link>
            <guid isPermaLink="false">https://medium.com/p/e14469c96d24</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Daniel Haile]]></dc:creator>
            <pubDate>Tue, 19 Dec 2023 23:52:06 GMT</pubDate>
            <atom:updated>2023-12-19T23:52:06.982Z</atom:updated>
            <content:encoded><![CDATA[<p>Why Angular Life Cycle?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*QcBFDO2X7pLkrzPdrDFj-Q.jpeg" /></figure><p>The Angular lifecycle is a series of events that occur throughout the existence of an Angular component. These lifecycle events provide developers with hooks to execute code at specific points in the component’s life.</p><p>The Angular lifecycle is essential for several reasons:</p><p>Initialization and Configuration:</p><p>ngOnChanges, ngOnInit: These events allow you to set up and configure the component when it’s created or when its inputs change. This is where you can perform tasks such as initializing properties or making API calls.</p><p>Change Detection:</p><p>ngDoCheck: Provides a hook for custom change detection logic. You can implement checks to detect changes that Angular might not automatically recognize.</p><p>Content Initialization:</p><p>ngAfterContentInit, ngAfterContentChecked: These events occur after the component’s content (like content projected using ng-content) has been initialized or checked. They are useful for operations dependent on the initialization or changes in content.</p><p>View Initialization:</p><p>ngAfterViewInit, ngAfterViewChecked: Occur after the component’s view has been initialized or checked. Useful for operations that rely on the view, like accessing child components.</p><p>Destruction:</p><p>ngOnDestroy: Executed just before the component is destroyed. It’s crucial for cleanup tasks, such as unsubscribing from observables or releasing resources to prevent memory leaks.</p><p>Performance Optimization:</p><p>Leveraging lifecycle hooks allows developers to optimize performance by executing code at specific moments. For instance, expensive operations can be deferred until the view is initialized, preventing unnecessary computations during change detection.</p><p>Integration with External Libraries:</p><p>When integrating Angular with external libraries or third-party components, understanding the Angular lifecycle is essential. It allows you to synchronize the lifecycle of Angular components with those of external components.</p><p>Observing and Reacting to Changes:</p><p>The lifecycle hooks provide developers with visibility into the state and changes of a component. This enables better debugging, logging, and understanding of how the component evolves over time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e14469c96d24" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Join the daily Quiz challenge below]]></title>
            <link>https://medium.com/@daniel-haile/join-the-daily-quiz-challenge-below-7db028f339d7?source=rss-c07a36e3119------2</link>
            <guid isPermaLink="false">https://medium.com/p/7db028f339d7</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Daniel Haile]]></dc:creator>
            <pubDate>Fri, 15 Dec 2023 18:23:58 GMT</pubDate>
            <atom:updated>2023-12-15T18:23:58.210Z</atom:updated>
            <content:encoded><![CDATA[<p>Join the daily Quiz challenge below</p><p><a href="https://www.youtube.com/channel/UCX5-wMpwzxzUMMfs7Xv5D6w/community">Daily Dev Quiz</a></p><p><strong><em>Subscribe for more….</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7db028f339d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tips for Angular Custom Pipes: Implementing Search Functionality for User Profiles]]></title>
            <link>https://medium.com/@daniel-haile/mastering-angular-custom-pipes-implementing-search-functionality-for-user-profiles-a5c3530fd17d?source=rss-c07a36e3119------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5c3530fd17d</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[custom-pipe]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[pipes]]></category>
            <dc:creator><![CDATA[Daniel Haile]]></dc:creator>
            <pubDate>Wed, 09 Aug 2023 06:26:36 GMT</pubDate>
            <atom:updated>2023-08-09T11:37:02.969Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n1C8mJQQEu2d7jo2jgoheA.jpeg" /></figure><p>A custom pipe in Angular is a way to transform and format data before it’s displayed in the user interface. It allows you to create reusable transformations for data, which can be applied in templates using the pipe operator (|). Custom pipes are especially useful when you need to perform specific data manipulations or filtering that are not available out of the box.</p><p>Here are some key points about custom pipes in Angular:</p><ol><li>Creation of Custom Pipes:</li></ol><ul><li>You can create a custom pipe by implementing the PipeTransform interface and providing a transform method in your class.</li><li>A pipe class is typically decorated with the @Pipe decorator, which specifies the pipe&#39;s name to be used in templates.</li></ul><p>2. Using Custom Pipes:</p><ul><li>Custom pipes are used in templates with the pipe operator (|). For example: {{ data | customPipe }}.</li><li>You can also pass arguments to custom pipes to customize their behavior: {{ data | customPipe: arg1: arg2 }}.</li></ul><p>3. Pipe Arguments and Pure Pipes:</p><ul><li>By default, Angular treats pipes as “pure,” which means they only run when the input value changes. This is done for performance optimization.</li><li>If a pipe takes arguments and the arguments change, the pipe is invoked.</li><li>You can set a pipe as “impure” by including pure: false in the @Pipe decorator. This makes the pipe run on every change detection cycle.</li></ul><p>4. Pipe Transformation Logic:</p><ul><li>The transform method in a custom pipe is where you define the logic to transform the input data.</li><li>The input data is the value passed to the pipe operator (|) in the template.</li></ul><p>5. Chaining Pipes:</p><ul><li>You can chain multiple pipes together in a template to apply different transformations sequentially: {{ data | pipe1 | pipe2 }}.</li></ul><p>6. Common Use Cases for Custom Pipes:</p><ul><li>Formatting dates and numbers.</li><li>Filtering and sorting lists of data.</li><li>Transforming text (uppercase, lowercase, title case).</li><li>Custom data manipulation.</li></ul><p>7. Pipe Decorator Options:</p><ul><li>The @Pipe decorator can have optional configuration options like pure for setting a pipe as impure.</li><li>Example: @Pipe({ name: &#39;customPipe&#39;, pure: false }).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dt-8i4eisWFYBKV3pYnHng.png" /></figure><ol><li>MyPipe Custom Pipe: This is a custom Angular pipe named MyPipe. It implements the PipeTransform interface and is used to filter an array of user profiles based on user input.</li></ol><pre>import { Pipe, PipeTransform } from &#39;@angular/core&#39;;<br>import { IProfile } from &#39;../profile-component/profile.model&#39;;<br><br>@Pipe({<br>  name: &#39;myPipe&#39;,<br>})<br>export class MyPipe implements PipeTransform {<br>  transform(value: IProfile[], userInput: string) {<br>    userInput = userInput ? userInput.toLowerCase() : &#39;&#39;;<br>    return userInput<br>      ? value.filter(<br>          (data) =&gt;<br>            data.firstname.toLowerCase().indexOf(userInput) &gt; -1 ||<br>            data.lastname.toLowerCase().indexOf(userInput) &gt; -1<br>        )<br>      : value;<br>  }<br>}</pre><p>2. Search Input and Display: In the HTML template, there’s an input field where users can type their search query. The search query is bound to the userInput property using two-way data binding ([(ngModel)]).</p><pre>&lt;input<br>  class=&quot;form-control&quot;<br>  type=&quot;search&quot;<br>  id=&quot;email&quot;<br>  placeholder=&quot;Search by user&#39;s First Name or Last Name...&quot;<br>  [(ngModel)]=&quot;userInput&quot;<br>/&gt;</pre><p>3. Search Result Statistics: The template displays the number of search results based on the user’s input. It calculates and displays the count of matching results and the total number of users.</p><pre>&lt;p&gt;<br>  Number of search result : {{ (userslist | myPipe: userInput).length }} out<br>  of {{ userslist.length }} total users<br>&lt;/p&gt;</pre><p>4. Search Result Table: The template uses the custom myPipe pipe to filter and display the user profiles that match the search input. The profiles are iterated using an *ngFor loop, and details for each user are displayed in a table row. The user&#39;s details are also linked to their profile page and a &quot;Delete User&quot; action.</p><pre>&lt;tr *ngFor=&quot;let user of userslist | myPipe: userInput; let index = index&quot;&gt;<br>  &lt;th scope=&quot;row&quot;&gt;{{ index + 1 }}&lt;/th&gt;<br>  &lt;td&gt;{{ user.firstname }}&lt;/td&gt;<br>  &lt;td&gt;{{ user.lastname }}&lt;/td&gt;<br>  &lt;td&gt;<br>    &lt;a style=&quot;color: blue&quot; [routerLink]=&quot;[&#39;/profile&#39;, user._id]&quot;&gt;User Details&lt;/a&gt;<br>    ||<br>    &lt;a style=&quot;color: #ff0000&quot; [routerLink]=&quot;&quot;&gt;Delete User&lt;/a&gt;<br>  &lt;/td&gt;<br>&lt;/tr&gt;</pre><p>5. Error Handling: If no matching results are found, a message in red is displayed to indicate a bad request.</p><pre>&lt;div *ngIf=&quot;(userslist | myPipe: userInput).length === 0&quot;&gt;<br>  &lt;p style=&quot;color: red&quot;&gt;Bad Request, Search Again!!&lt;/p&gt;<br>&lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*idIISb5_l9zTtzEf5h_toA.png" /></figure><p>6. Total Users Count: At the end of the template, the total number of users in the userslist array is displayed.</p><pre>Total users are: {{ userslist.length }}</pre><p>Thank you for reading! Follow me on <a href="https://medium.com/@daniel-haile">Medium</a> for more useful articles. If you’ve any questions, drop it on the comment section!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5c3530fd17d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to implement Password Visibility Toggle in Angular? A Step-by-Step Guide]]></title>
            <link>https://medium.com/@daniel-haile/enhancing-password-visibility-toggle-in-angular-a-step-by-step-guide-b5e149dee0d4?source=rss-c07a36e3119------2</link>
            <guid isPermaLink="false">https://medium.com/p/b5e149dee0d4</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-forms]]></category>
            <category><![CDATA[reactive-forms]]></category>
            <dc:creator><![CDATA[Daniel Haile]]></dc:creator>
            <pubDate>Thu, 03 Aug 2023 04:31:36 GMT</pubDate>
            <atom:updated>2023-08-04T04:48:06.047Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*stwmYalEdlv3Z9dgMMZkhw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TngjcHBpc8i3yt1JP16NvA.png" /></figure><p>Steps to implement password visibility toggle on Angular Reactive Forms:</p><ol><li>Set up a boolean variable showPassword and initialize it as false.as shown below on line 1.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*n3-vZao7pBbP3PsTgjEFOw.jpeg" /></figure><ol><li>Create a function togglePasswordVisibility() to toggle the value of showPassword between true and false. As shown on the above screenshot line 12.</li><li>In the HTML file, use an input field with the type attribute dynamically bound to showPassword ? &#39;text&#39; : &#39;password&#39;. This changes the input field type between text and password based on the value of showPassword.</li><li>Add a &lt;span&gt; element with a glyphicon class to display an eye icon.</li><li>Use Angular’s ngClass directive to toggle the class between &#39;glyphicon-eye-open&#39; and &#39;glyphicon-eye-close&#39; based on the value of showPassword.</li><li>Bind the (click) event of the &lt;span&gt; to the togglePasswordVisibility() function, so when the icon is clicked, it toggles the password visibility.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R6NabpnJ6PBLPcft8qc1Mg.jpeg" /></figure><p>6. Create a CSS class for the eye icon (glyphicon) to set its size and style</p><pre>.password-input-wrapper {<br>  position: relative;<br>}<br><br>.password-input-wrapper .glyphicon {<br>  position: absolute;<br>  top: 10px;<br>  right: 10px;<br>  cursor: pointer;<br>  font-size: 24px;<br>}</pre><p>Thank you for reading! Follow me on <a href="https://medium.com/@daniel-haile"><strong><em>Medium</em></strong></a> for more useful articles. If you’ve any questions, drop it on the comment section!</p><p>Happy Coding!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b5e149dee0d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to implement Angular Route Guards?]]></title>
            <link>https://medium.com/@daniel-haile/how-to-implement-angular-route-guards-40a3f99466c4?source=rss-c07a36e3119------2</link>
            <guid isPermaLink="false">https://medium.com/p/40a3f99466c4</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Daniel Haile]]></dc:creator>
            <pubDate>Sat, 29 Jul 2023 05:15:14 GMT</pubDate>
            <atom:updated>2023-08-03T05:20:51.110Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*AChkyFE6LMfe6t4QZ-DnGw.png" /></figure><blockquote>Angular Guards are mechanisms that allow you to control access to certain routes in your Angular application.</blockquote><blockquote>They are used to protect routes based on specific conditions and are executed before a route is activated.</blockquote><p>Angular provides several types of guards:</p><ol><li><strong>CanActivate:</strong> This guard is used to determine if a route can be activated and accessed. It checks if the user is allowed to navigate to a specific route based on certain conditions, such as authentication status, user role, or any custom logic. If the CanActivate guard returns true, the route is accessible; otherwise, if it returns false or a UrlTree object, the navigation is blocked, and the user is redirected to another route.</li><li><strong>CanActivateChild:</strong> Similar to CanActivate, but it applies to child routes. It is used to control access to child routes of a specific parent route.</li><li><strong>CanDeactivate:</strong> This guard is used to determine if a user can navigate away from a route. It checks if the user can safely leave the current route, possibly prompting them with a confirmation dialog if there are unsaved changes or incomplete actions.</li><li><strong>CanLoad:</strong> This guard is used when implementing lazy-loaded modules. It determines if a lazy-loaded module can be loaded based on certain conditions, such as authentication status or user roles.</li><li><strong>Resolve:</strong> The Resolve guard is used to fetch necessary data for a route before the route is activated. It waits for the data to be resolved before proceeding with the route activation, ensuring that the required data is available when the component is initialized.</li></ol><pre>// guards/user.guard.ts<br><br>import { Injectable } from &#39;@angular/core&#39;;<br>import { ActivatedRouteSnapshot, CanActivate, Router } from &#39;@angular/router&#39;;<br><br>@Injectable()<br>export class UserGuardService implements CanActivate {<br>  token: string | null = &#39;&#39;;<br>  role: string | null = &#39;&#39;;<br><br>  constructor(private router: Router) {}<br><br>  canActivate(route: ActivatedRouteSnapshot): boolean {<br>    this.token = localStorage.getItem(&#39;token&#39;);<br>    this.role = localStorage.getItem(&#39;RoleType&#39;);<br><br>    if (this.token == null) {<br>      this.router.navigate([&#39;/login&#39;]);<br>      return false;<br>    }<br>    if (this.token !== null &amp;&amp; this.role === &#39;Admin&#39;) {<br>      this.router.navigate([&#39;/admindashboard&#39;]);<br>      return false;<br>    }<br>    if (this.token !== null &amp;&amp; this.role === &#39;User&#39;) {<br>      this.router.navigate([&#39;/userdashboard&#39;]);<br>      return false;<br>    }<br><br>    return true; // Allow the route to be activated if none of the previous conditions match<br>  }<br>}</pre><blockquote><strong>NOTE:</strong> a brief explanation of when to return <em>true</em> or <em>false</em> in the <em>canActivate</em> method:</blockquote><ol><li>Return true: If the guard returns true, it allows the route to be activated, and the navigation will continue as usual.</li><li>Return false: If the guard returns false, it prevents the route from being activated, and the navigation will be stopped or redirected based on the guard logic.</li></ol><p>When to return false:</p><ul><li>If the user does not have the necessary credentials or authorization to access a specific route, you can return false to prevent them from accessing that route. In this case, you may want to redirect the user to a login page or another appropriate page.</li><li>If the user is already authenticated and you want to redirect them to a different page based on their role or some other condition, you can return false and use the Router.navigate() method to redirect them to the desired page.</li></ul><p>When to return true:</p><ul><li>If the user has the necessary credentials or authorization to access a specific route, you should return true to allow the route to be activated, and the navigation will continue as usual.</li><li>If the guard does not have any specific conditions to check or restrictions to apply, and you simply want to allow the route to be activated unconditionally, you can return true.</li></ul><pre><br>// app-routing.module.ts<br><br><br>const routes: Routes = [<br>  { path: &#39;login&#39;, loadChildren: () =&gt; import(&#39;./login/login.module&#39;).then(m =&gt; m.LoginModule) },<br>  { path: &#39;signup&#39;, loadChildren: () =&gt; import(&#39;./signup/signup.module&#39;).then(m =&gt; m.SignupModule) },<br>  {<br>    path: &#39;admindashboard&#39;,<br>    loadChildren: () =&gt; import(&#39;./admin-dashboard/admin-dashboard.module&#39;).then(m =&gt; m.AdminDashboardModule),<br>    canActivate: [UserGuardService], // Apply UserGuardService for AdminDashboard route<br>    data: { expectedRole: &#39;Admin&#39; }, // You can pass additional data like the expected role<br>  },<br>  {<br>    path: &#39;userdashboard&#39;,<br>    loadChildren: () =&gt; import(&#39;./user-dashboard/user-dashboard.module&#39;).then(m =&gt; m.UserDashboardModule),<br>    canActivate: [UserGuardService], // Apply UserGuardService for UserDashboard route<br>    data: { expectedRole: &#39;User&#39; }, // You can pass additional data like the expected role<br>  },<br>  { path: &#39;&#39;, redirectTo: &#39;/login&#39;, pathMatch: &#39;full&#39; }, // Redirect to login by default<br>  { path: &#39;**&#39;, redirectTo: &#39;/login&#39;, pathMatch: &#39;full&#39; }, // Redirect to login for any other unknown route<br>];<br><br>@NgModule({<br>  imports: [<br>    RouterModule.forRoot(routes),<br>    LoginModule,<br>    SignupModule,<br>    AdminDashboardModule,<br>    UserDashboardModule,<br>  ],<br>  exports: [RouterModule],<br>})<br>export class AppRoutingModule {}</pre><blockquote>On the above <strong><em>AppRoutingModule</em></strong> that defines the routing configuration for our Angular application. It uses lazy loading for feature modules, which is a technique to load modules only when they are needed, reducing the initial loading time of our application.</blockquote><blockquote>The loadChildren property is used for lazy loading. When the user navigates to a route defined with loadChildren, the specified module is loaded on-demand instead of being bundled with the main application.</blockquote><blockquote>Thank you for reading! Follow me on <a href="https://medium.com/@daniel-haile"><strong><em>Medium</em></strong></a> for more useful articles. If you’ve any questions, drop it on the comment section!</blockquote><blockquote>Happy Coding!!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40a3f99466c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Implement Angular Service for Reactive Forms Login Page?]]></title>
            <link>https://medium.com/@daniel-haile/angular-service-implementation-for-login-page-2c258b64fa74?source=rss-c07a36e3119------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c258b64fa74</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-ui]]></category>
            <dc:creator><![CDATA[Daniel Haile]]></dc:creator>
            <pubDate>Thu, 27 Jul 2023 17:25:00 GMT</pubDate>
            <atom:updated>2023-07-28T08:02:05.020Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZbcX3hl60YPbkV1z0CB3qw.png" /></figure><ul><li>Angular services are classes that provide common functionality and data to multiple components in an Angular application.</li><li>Services act as singletons, meaning they are shared and only instantiated once throughout the application’s lifecycle.</li><li>Services can be injected into components, other services, or modules using dependency injection.</li><li>They are commonly used to fetch data from APIs, handle business logic, and manage application state.</li><li>Services promote code reusability, maintainability, and separation of concerns in Angular applications.</li><li>To create a service, use the @Injectable() decorator and define the business logic within its methods.</li><li>Services should be registered in the providers array of the AppModule or within a specific component’s providers to be accessible throughout the app.</li></ul><pre><br>// login.service.ts<br><br>import { Injectable } from &#39;@angular/core&#39;;<br>import { Observable } from &#39;rxjs/&#39;;<br><br>import { HttpClient } from &#39;@angular/common/http&#39;;<br>import { Router } from &#39;@angular/router&#39;;<br>import { ILogin } from &#39;../user-models/login.model&#39;;<br><br>@Injectable()<br>export class LoginService {<br>  private LOGIN_URL: string = &#39;http://localhost:8088/user/login&#39;;<br>  loginError: any;<br>  constructor(private http: HttpClient, private router: Router) {}<br><br>  loginUser(user: ILogin): Observable&lt;ILogin&gt; {<br>    return this.http.post&lt;ILogin&gt;(this.LOGIN_URL, user);<br>  }<br><br>  logout() {<br>    localStorage.removeItem(&#39;token&#39;);<br>    localStorage.removeItem(&#39;RoleType&#39;);<br>    this.router.navigate([&#39;/login&#39;]);<br>  }<br>  isLoggedIn() {<br>    return !!localStorage.getItem(&#39;token&#39;);<br>  }<br>}</pre><pre>// user-models/login.model.ts<br><br>/**<br> * @author Daniel Haile<br> * @Interface<br> */<br><br> export interface ILogin {<br>   email: string;<br>   password: string;<br>   role : string<br> }</pre><p>Thanks for reading!<br>Happy Coding!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c258b64fa74" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to implement Login Angular Component using Reactive Form?]]></title>
            <link>https://medium.com/@daniel-haile/how-to-implement-login-angular-component-using-reactive-form-380391f419c3?source=rss-c07a36e3119------2</link>
            <guid isPermaLink="false">https://medium.com/p/380391f419c3</guid>
            <category><![CDATA[reactive-forms]]></category>
            <category><![CDATA[angular-ui]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Daniel Haile]]></dc:creator>
            <pubDate>Thu, 27 Jul 2023 04:18:50 GMT</pubDate>
            <atom:updated>2024-01-14T21:22:32.581Z</atom:updated>
            <content:encoded><![CDATA[<ol><li>Use Reactive Forms to create a Login Angular Component.</li><li>Define form controls for email and password fields with validation.</li><li>Bind form controls in the HTML template.</li><li>Implement a method to handle form submission.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*26LkMOggszRRmpnLwcHIqw.png" /></figure><pre>// Login Angular Component<br><br><br>import { Component, OnDestroy, OnInit } from &#39;@angular/core&#39;;<br>import { LoginService } from &#39;../../../services/auth-users-service/login.service&#39;;<br>import {<br>  FormBuilder,<br>  FormGroup,<br>  Validators,<br>} from &#39;@angular/forms&#39;;<br>import { Router } from &#39;@angular/router&#39;;<br>import { finalize } from &#39;rxjs/operators&#39;;<br>import { Subscription } from &#39;rxjs&#39;;<br><br>@Component({<br>  selector: &#39;lib-login&#39;,<br>  templateUrl: &#39;./login.component.html&#39;,<br>  styleUrls: [&#39;./login.component.scss&#39;],<br>})<br>export class LoginComponent implements OnInit, OnDestroy {<br>  loginForm!: FormGroup;<br>  loginError: string = &#39;&#39;;<br>  subscription!: Subscription;<br>  loading: boolean = false;<br><br>  constructor(<br>    private formBuilder: FormBuilder,<br>    private loginService: LoginService,<br>    private router: Router<br>  ) {}<br><br>  ngOnInit(): void {<br>    this.buildForm();<br>  }<br><br>  buildForm(): void {<br>    this.loginForm = this.formBuilder.group({<br>      email: [<br>        &#39;&#39;,<br>        [<br>          Validators.required,<br>          Validators.pattern(&#39;^([a-zA-Z0-9]+)@([a-zA-Z0-9]+).([a-zA-Z]{2,3})$&#39;),<br>        ],<br>      ],<br>      password: [&#39;&#39;, Validators.required],<br>    });<br>  }<br><br>  userLogin(): void {<br>    if (this.loginForm.valid) {<br>      console.log(&#39;this.loginForm.valid&#39;, this.loginForm.valid);<br>      this.loading = true; // Start the loading spinner<br><br>      this.subscription = this.loginService<br>        .loginUser(this.loginForm.value)<br>        .pipe(<br>          finalize(() =&gt; {<br>            this.loading = false; //Stop the loading spinner<br>          })<br>        )<br>        .subscribe({<br>          next: (res: any) =&gt; {<br>            console.log(&#39;Response:&#39;, res);<br>            if (res.success) {<br>              console.log(&#39;Show me the success - &#39;, res.role, res)<br>              localStorage.setItem(&#39;RoleType&#39;, res.role);<br>              this.loginError = &#39;&#39;;<br>              this.loginForm.reset();<br>              this.navigateDashboard(res.role);<br>            } else {<br>                this.loginError = &#39;Invalid email and password combination!&#39;;<br>              }<br>            <br>          },<br>          error: (error: any) =&gt; {<br>            this.loginError = &#39;An error occurred during login.&#39;;<br>            console.error(&#39;Login Error:&#39;, error);<br>          },<br>        });<br>    }<br>  }<br><br>  <br>  navigateDashboard(role: string): void {<br>    const dashboardRoute =<br>      role === &#39;admin&#39; ? &#39;/admindashboard&#39; : &#39;/userdashboard&#39;;<br>    this.router.navigate([dashboardRoute]);<br>    console.log(`${role} dashboard route`);<br>  }<br><br>  ngOnDestroy(): void {<br>    if (!this.subscription) {<br>      return;<br>    }else{<br>      return this.subscription.unsubscribe();<br>    }<br>  }<br>}<br><br><br><br><br></pre><p>Thank you for reading! Follow me on <a href="https://medium.com/@daniel-haile"><strong><em>Medium</em></strong></a> for more useful articles. If you’ve any questions, drop it on the comment section!</p><p>Happy Coding!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=380391f419c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to implement login using nodejs, expressjs and mongoose]]></title>
            <link>https://medium.com/@daniel-haile/login-implementation-using-nodejs-expressjs-and-mongoose-7f5bca50428e?source=rss-c07a36e3119------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f5bca50428e</guid>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[mongoose]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Daniel Haile]]></dc:creator>
            <pubDate>Thu, 27 Jul 2023 03:59:28 GMT</pubDate>
            <atom:updated>2023-08-04T23:13:35.967Z</atom:updated>
            <content:encoded><![CDATA[<pre>// controller/user.controller.js <br><br>const User = require(&quot;../models/user.models.js&quot;);<br>const jwt = require(&quot;jsonwebtoken&quot;);<br>require(&quot;dotenv&quot;).config();<br><br>exports.login = async (req, res) =&gt; {<br>  try {<br>    const { email, password } = req.body;<br>    const user = await User.findOne({ email }); // Use findOne with email as a query object<br><br>    if (!user) {<br>      return res.status(404).json({ message: &quot;Email not found&quot; });<br>    }<br><br>    const isMatch = await bcrypt.compare(password, user.password);<br>    if (!isMatch) {<br>      return res.status(401).json({ message: &quot;Wrong Password&quot; });<br>    }<br><br>    const token = jwt.sign(<br>      {<br>        id: user._id,<br>        dzID: user.dzID,<br>        email: user.email,<br>        password: user.password,<br>        role: user.role,<br>      },<br>      process.env.JWT_SECRET,<br>      { expiresIn: process.env.TOKEN_EXPIRATION }<br>    );<br><br>    console.log(&quot;token&quot;, token);<br><br>    return res.status(200).json({<br>      status: &quot;success&quot;,<br>      message: &quot;You&#39;re successfully signed in...&quot;,<br>      token: token,<br>    });<br>  } catch (err) {<br>    console.log(&quot;ERROR&quot;, err);<br>    return res.status(500).json({ status: &quot;error&quot;, message: err.message });<br>  }<br>};</pre><figure><img alt="Implementing login functionality with Node.js and Mongoose involves creating a User model schema to store user data securely in MongoDB. Users can register by providing necessary information, and their passwords are hashed using bcrypt before storage. Upon login, the system validates credentials, compares hashed passwords, and generates a session or token for authenticated access to protected routes. Security measures, such as encryption and error handling, are applied to ensure a safe and seaml" src="https://cdn-images-1.medium.com/max/880/1*6vfVDA-9P3m1y4DddcFWoA.png" /></figure><pre>// routes/user.routes.js<br>const express = require(&quot;express&quot;);<br>const UserController = require(&quot;../controllers/user.controllers&quot;);<br>const router = express.Router();<br><br>router.post(&quot;/login&quot;,  UserController.login);</pre><pre>// app.js<br><br>const express = require(&#39;express&#39;);<br>const cors = require(&#39;cors&#39;);<br>const userRoutes = require(&quot;./routes/user.routes&quot;);<br>const initiateMyMongoServer = require(&quot;./config/database&quot;);<br>const landingPageRoutes = require(&#39;./routes/landingPages.routes&#39;);<br><br>require(&quot;dotenv&quot;).config();<br><br>const app = express();<br><br>//db connection<br>initiateMyMongoServer();<br><br>//Port number is 8080<br>const PORT = 8000;<br>app.use(express.json())<br>app.use(cors());<br>app.use(&quot;/uploads&quot;, express.static(&quot;uploads&quot;));<br><br><br>// Register your routes<br>app.use(&#39;/user&#39;, userRoutes);<br><br>app.listen(PORT, ()=&gt; console.log(&#39;listening on port - &#39;, PORT))</pre><pre>// config/database.js <br><br>const mongoose = require(&quot;mongoose&quot;);<br>require(&quot;dotenv&quot;).config();<br><br>const myDatabaseMongoServer = () =&gt; {<br>  mongoose<br>    .connect(process.env.DATABASE_URL, {<br>      useNewUrlParser: true,<br>      useUnifiedTopology: true,<br>    })<br>    .then(() =&gt; console.log(&quot;Database is successfully connected...&quot;))<br>    .catch((err) =&gt; {<br>      console.log(&quot;Database is NOT connected...&quot;, err.message);<br>    });<br>};<br><br>module.exports = myDatabaseMongoServer;</pre><p>Thank you for reading! Follow me on <a href="https://medium.com/@daniel-haile">Medium</a> for more useful articles. If you’ve any questions, drop it on the comment section!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f5bca50428e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>