<?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 hisham abd elshafouk on Medium]]></title>
        <description><![CDATA[Stories by hisham abd elshafouk on Medium]]></description>
        <link>https://medium.com/@hish.abdelshafouk?source=rss-6a9f12465ba7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*efF0KWFwO1AUGTOE</url>
            <title>Stories by hisham abd elshafouk on Medium</title>
            <link>https://medium.com/@hish.abdelshafouk?source=rss-6a9f12465ba7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 19:54:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hish.abdelshafouk/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[Understanding JavaScript Engines]]></title>
            <link>https://medium.com/@hish.abdelshafouk/understanding-javascript-engines-004629f3a2b9?source=rss-6a9f12465ba7------2</link>
            <guid isPermaLink="false">https://medium.com/p/004629f3a2b9</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[garbage-collection]]></category>
            <category><![CDATA[jit]]></category>
            <dc:creator><![CDATA[hisham abd elshafouk]]></dc:creator>
            <pubDate>Fri, 31 May 2024 13:48:14 GMT</pubDate>
            <atom:updated>2024-05-31T14:35:31.236Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hqr-a8cPPnhh7Ug_lsuEIg.jpeg" /></figure><p>JavaScript engines are responsible for executing JavaScript code efficiently. They transform high-level JavaScript code into machine code that can be directly executed by the computer’s processor. This guide provides an in-depth look at how JavaScript engines function, covering parsing, compilation, execution, optimization, and memory management.</p><h3>Key Components of JavaScript Engines</h3><ol><li><strong>Parser</strong></li><li><strong>Interpreter</strong></li><li><strong>JIT Compiler</strong></li><li><strong>Garbage Collector</strong></li><li><strong>Profiler</strong></li></ol><h3>Parsing 🔄</h3><p>The parsing phase converts the JavaScript source code into a format that the engine can understand and manipulate.</p><ul><li><strong>Lexical Analysis (Tokenization)</strong>: The engine breaks down the source code into a series of tokens. Tokens are the smallest units of meaning, such as keywords (let, function), operators (+, -), literals (42, &#39;hello&#39;), and punctuation (;, ,).</li><li><strong>Syntax Analysis (Parsing)</strong>: The tokens are then arranged into an Abstract Syntax Tree (AST). The AST represents the hierarchical structure of the code, showing the relationships between different parts of the code.</li></ul><h3>Compilation ⚙️</h3><p>Modern JavaScript engines use a combination of interpretation and Just-In-Time (JIT) compilation to balance the need for fast startup and optimal execution speed.</p><ul><li><strong>Bytecode Generation</strong>: The interpreter first converts the AST into bytecode, a low-level representation of the code that is more efficient to execute than the original JavaScript source.</li><li><strong>JIT Compilation</strong>: The JIT compiler takes the bytecode and compiles it into machine code. There are usually two stages:</li></ul><ol><li><strong>Baseline JIT</strong>: Quickly compiles bytecode to machine code with minimal optimizations, allowing for faster initial execution.</li><li><strong>Optimizing JIT</strong>: Monitors the running code, identifies hot code paths, and recompiles these paths with more aggressive optimizations.</li></ol><h3>Execution ⚡</h3><p>The engine executes the machine code generated by the JIT compiler. During execution, several important tasks are performed:</p><ul><li><strong>Function Execution Context</strong>: The engine manages execution contexts, which contain information about variable scope, the value of this, and the function’s arguments. Each function call creates a new execution context.</li><li><strong>Call Stack</strong>: JavaScript engines use a call stack to keep track of function calls. Each call adds a new frame to the stack, and returning from a function removes the top frame from the stack.</li><li><strong>Event Loop</strong>: JavaScript is single-threaded, meaning it can only execute one piece of code at a time. The event loop manages asynchronous operations by queuing tasks and executing them sequentially. When the call stack is empty, the event loop picks the next task from the queue and executes it.</li></ul><h3>Optimization Techniques ✨</h3><p>JavaScript engines employ various optimization techniques to improve performance:</p><ul><li><strong>Inline Caching</strong>: The engine optimizes property access by caching the locations of frequently accessed properties. This reduces the overhead of property lookups.</li><li><strong>Hidden Classes</strong>: The engine creates hidden classes to optimize object property access. Objects with the same properties are given the same hidden class, allowing the engine to optimize property access based on these hidden classes.</li><li><strong>Type Feedback</strong>: The engine collects type information during execution and uses this information to generate optimized machine code.</li><li><strong>Deoptimization</strong>: If assumptions made during optimization are proven wrong (e.g., a property type changes), the engine can deoptimize the code and revert to a less optimized version.</li></ul><h3>Memory Management 💾</h3><p>JavaScript engines use automatic memory management, which includes allocation and garbage collection:</p><ul><li><strong>Memory Allocation</strong>: The engine allocates memory for objects, arrays, and other data structures as needed.</li><li><strong>Garbage Collection</strong>: The garbage collector reclaims memory that is no longer in use. JavaScript engines typically use a combination of generational and incremental garbage collection techniques.</li><li><strong>Generational Garbage Collection</strong>: Divides objects into different generations based on their age. Young objects are collected more frequently than old objects.</li><li><strong>Incremental Garbage Collection</strong>: Breaks the garbage collection process into smaller steps, reducing the impact on application performance.</li></ul><h3>Example: V8 Engine</h3><p>V8 is the JavaScript engine used in Google Chrome and Node.js. It is one of the most advanced JavaScript engines and employs several sophisticated techniques to optimize performance.</p><ul><li><strong>Ignition</strong>: V8’s interpreter that generates bytecode from the AST. It focuses on quickly starting the execution of JavaScript code.</li><li><strong>TurboFan</strong>: V8’s optimizing compiler that takes the bytecode and compiles it into highly optimized machine code. TurboFan applies advanced optimization techniques, such as inline caching, hidden classes, and type feedback.</li><li><strong>Orinoco</strong>: V8’s garbage collector that uses a combination of generational and incremental garbage collection techniques to manage memory efficiently.</li></ul><h3>Performance Considerations</h3><p>JavaScript engine performance can be influenced by various factors, including:</p><ul><li><strong>Code Structure</strong>: Well-structured and modular code can be optimized more effectively by the engine.</li><li><strong>Hot Paths</strong>: Frequently executed code paths are more likely to be optimized by the JIT compiler.</li><li><strong>Memory Usage</strong>: Efficient memory usage can reduce the overhead of garbage collection.</li><li><strong>Concurrency</strong>: While JavaScript itself is single-threaded, engines optimize performance through concurrency, such as using multiple threads for garbage collection and JIT compilation.</li></ul><h3>Conclusion</h3><p>JavaScript engines are highly optimized systems designed to execute JavaScript code efficiently. They use a combination of parsing, JIT compilation, interpretation, and various optimization techniques to achieve fast execution. Understanding these internal mechanisms can help developers write more efficient and optimized JavaScript code, leading to better performance in their applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=004629f3a2b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Event Loop: JavaScript’s Asynchronous Task Management Mechanism]]></title>
            <link>https://medium.com/@hish.abdelshafouk/event-loop-javascripts-asynchronous-task-management-mechanism-7d25ad608c71?source=rss-6a9f12465ba7------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d25ad608c71</guid>
            <category><![CDATA[callback]]></category>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[asynchronous]]></category>
            <dc:creator><![CDATA[hisham abd elshafouk]]></dc:creator>
            <pubDate>Wed, 29 Nov 2023 12:05:14 GMT</pubDate>
            <atom:updated>2023-11-29T12:05:14.694Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OJ25MGWc4j-FEoP-" /><figcaption>Photo by <a href="https://unsplash.com/@tine999?utm_source=medium&amp;utm_medium=referral">Tine Ivanič</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The event loop in JavaScript is a fundamental mechanism managing asynchronous operations. It ensures smooth execution by handling tasks in a non-blocking manner. When an asynchronous task, like fetching data or timers, completes, it’s placed in a queue. The event loop continuously checks this queue, executing tasks one by one in a sequence.</p><p>Its primary benefit lies in preventing the blocking of the main thread, enabling the browser to remain responsive while handling multiple operations simultaneously. This mechanism allows for efficient handling of I/O operations and long-running tasks without freezing the user interface, enhancing the overall user experience in web applications.</p><h4>How:</h4><p>let’s dive a bit deeper into how the event loop works under the hood in JavaScript:</p><ol><li><strong>Call Stack:</strong> JavaScript has a call stack that keeps track of the functions being executed. When a function is called, it’s added to the stack. As functions complete, they’re removed from the stack.</li><li><strong>Web APIs and Callbacks:</strong> When you make an asynchronous request, like setTimeout or an <strong>AJAX </strong>call, it&#39;s handed off to the browser&#39;s Web APIs to execute. Meanwhile, the rest of your code keeps running.</li><li><strong>Callback Queue:</strong> Once the Web API finishes its task, it places a callback function related to that task in the callback queue.</li><li><strong>Event Loop:</strong> The event loop constantly checks if the call stack is empty. If it is, it takes the first function in the callback queue and pushes it onto the call stack to be executed.</li><li><strong>Execution: </strong>The function retrieved from the callback queue is executed, and if it has more asynchronous tasks, the process repeats.</li></ol><p>This cycle continues — call stack -&gt; Web APIs -&gt; callback queue -&gt; event loop — allowing asynchronous tasks to be handled without blocking the main thread. This mechanism ensures that while heavy operations are underway, the browser remains responsive to user interactions.</p><h4>Example:</h4><p>Let’s illustrate the event loop with a simple JavaScript example involving setTimeout, which simulates an asynchronous operation.</p><pre>console.log(&#39;Start&#39;);<br><br>setTimeout(function() {<br>  console.log(&#39;Inside setTimeout callback&#39;);<br>}, 0);<br><br>console.log(&#39;End&#39;);</pre><ol><li>Start Execution: The code starts executing. &#39;Start&#39; is logged to the console.</li><li>setTimeout: The setTimeout function is encountered. It schedules the callback function to be executed after a minimum of 0 milliseconds. However, it doesn’t block the code execution; it continues immediately to the next line.</li><li>‘End’: &#39;End&#39; is logged to the console.</li></ol><p>At this point, the call stack is empty.</p><ol><li>Event Loop: The event loop continuously checks if the call stack is empty. When it is empty, it picks up the callback from the setTimeout that has finished its waiting time and places it in the callback queue.</li><li>Callback Queue: The callback function console.log(&#39;Inside setTimeout callback&#39;) is placed in the callback queue.</li><li>Execution: As the call stack is empty, the event loop takes the function from the callback queue and pushes it onto the call stack.</li><li>Logging: &#39;Inside setTimeout callback&#39; is logged to the console.</li></ol><p><strong>Several Web APIs in browsers utilize the event loop to handle asynchronous tasks. Some of the notable ones include:</strong></p><ol><li><strong>setTimeout and setInterval:</strong> These APIs schedule code execution after a specified delay or at regular intervals, respectively.</li><li><strong>XMLHttpRequest: </strong>The classic way of making asynchronous HTTP requests in JavaScript.</li><li><strong>fetch API:</strong> A modern replacement for XMLHttpRequest that provides a more powerful and flexible interface for making HTTP requests.</li><li><strong>Promises:</strong> Although not Web APIs per se, promises are a part of JavaScript’s asynchronous functionality that works in conjunction with the event loop, allowing smoother handling of asynchronous operations.</li><li><strong>WebSockets:</strong> Used for establishing a bidirectional communication channel between a client and a server, enabling real-time data transfer.</li><li><strong>DOM Events:</strong> Events like click, submit, change, etc., are handled asynchronously by the event loop when they occur in the browser.</li><li><strong>Geolocation API:</strong> Provides location information about the user’s device asynchronously.</li></ol><h4>Conclusion:</h4><p>The event loop in JavaScript is the engine behind handling asynchronous tasks, ensuring smooth execution without blocking the main thread. It orchestrates the flow of operations, leveraging Web APIs to handle tasks like timers, I/O operations, and events. This mechanism enables JavaScript to manage multiple tasks concurrently, enhancing performance and responsiveness in web applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d25ad608c71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering User Profile Editing with Angular: A Hands-On Guide]]></title>
            <link>https://medium.com/@hish.abdelshafouk/mastering-user-profile-editing-with-angular-a-hands-on-guide-19119edf1eec?source=rss-6a9f12465ba7------2</link>
            <guid isPermaLink="false">https://medium.com/p/19119edf1eec</guid>
            <category><![CDATA[input-field]]></category>
            <category><![CDATA[reactive]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[reactive-forms]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[hisham abd elshafouk]]></dc:creator>
            <pubDate>Tue, 28 Nov 2023 12:20:08 GMT</pubDate>
            <atom:updated>2023-11-28T12:25:57.269Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3C-t-tDvEc3WdsHy" /><figcaption>Photo by <a href="https://unsplash.com/@chrisjoelcampbell?utm_source=medium&amp;utm_medium=referral">Christopher Campbell</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Welcome to the User Profile Editor! Get ready to dive into a hands-on experience where you’ll master editing profiles using Angular. Discover how to effortlessly update details, preview images in real-time, and validate information dynamically, empowering you to craft seamless user experiences.</p><h3>Step 1: Set Up an Angular Project</h3><p>To initiate an Angular project using Angular CLI for building the user profile edit form.</p><p><strong>Install Angular CLI (Command Line Interface):</strong></p><pre>npm install -g @angular/cli</pre><p><strong>Create a New Angular Project:</strong></p><pre>ng new user-profile-editor</pre><p>This command will create a new Angular project named user-profile-editor.</p><p><strong>Navigate to the Project Directory:</strong></p><pre>cd user-profile-editor</pre><p><strong>Serve the Angular App:</strong></p><pre>ng serve</pre><p>This command will build the application and start a development server at <a href="http://localhost:4200.">http://localhost:4200.</a></p><h4>Explanation:</h4><ul><li>Angular CLI simplifies the process of creating, developing, and maintaining Angular applications by providing commands to generate components, services, modules, etc.</li><li>The ng new command initializes a new Angular project with the default project structure.</li><li>Serving the application using ng serve hosts the application on a local development server, allowing you to view and test it in a web browser.</li></ul><h3>Step 2: Generate the Profile Edit Component</h3><p>To create a specific component to manage the user profile editing functionality.</p><p><strong>Generate a New Component:</strong></p><pre>ng generate component profile-edit</pre><h4>Explanation:</h4><ul><li>The ng generate component command generates a new Angular component along with its associated files (HTML, CSS/SCSS, TypeScript, and a test file).</li><li>This component will serve as the UI and logic for editing user profiles, handling form data, and interacting with the user.</li></ul><h3>Step 3: Reactive Form Setup</h3><p>To create a Reactive Form for managing user profile data within the Profile Edit component.</p><p><strong>Import Required Modules:</strong></p><p>In the profile-edit.component.ts file:</p><pre>import { FormBuilder, FormGroup, Validators } from &#39;@angular/forms&#39;;</pre><p><strong>Initialize Form in the Component Class:</strong></p><pre>export class ProfileEditComponent implements OnInit {<br>  profileForm: FormGroup;<br><br>  constructor(private formBuilder: FormBuilder) { }<br><br>  ngOnInit() {<br>    this.profileForm = this.formBuilder.group({<br>      // Define form controls here<br>    });<br>  }<br>}</pre><h4>Explanation:</h4><ul><li>FormBuilder, FormGroup, and Validators are imported from @angular/forms.</li><li>FormBuilder is a service that helps in building form groups and controls.</li><li>FormGroup represents a collection of form controls, while Validators provide various validation functions.</li><li>Inside the ngOnInit method, the profileForm is initialized as a FormGroup using formBuilder.group().</li></ul><h3>Step 4: Form Initialization and HTML Template</h3><p>To create form controls and their representation in the HTML template for editing user profile data.</p><p><strong>Initialize Form Controls in </strong><strong>ngOnInit():</strong></p><p>Inside ngOnInit() in profile-edit.component.ts:</p><pre>this.profileForm = this.formBuilder.group({<br>  profileImage: [&#39;&#39;], // Placeholder for profile image<br>  name: [&#39;&#39;, Validators.required],<br>  email: [&#39;&#39;, [Validators.required, Validators.email]],<br>  password: [&#39;&#39;, Validators.minLength(6)]<br>});</pre><p><strong>Create HTML Form Controls in </strong><strong>profile-edit.component.html:</strong></p><pre>&lt;form [formGroup]=&quot;profileForm&quot; (ngSubmit)=&quot;onSubmit()&quot;&gt;<br>  &lt;div&gt;<br>    &lt;label for=&quot;profileImage&quot;&gt;Profile Image:&lt;/label&gt;<br>    &lt;input type=&quot;file&quot; id=&quot;profileImage&quot; formControlName=&quot;profileImage&quot;&gt;<br>  &lt;/div&gt;<br>  &lt;div&gt;<br>    &lt;label for=&quot;name&quot;&gt;Name:&lt;/label&gt;<br>    &lt;input type=&quot;text&quot; id=&quot;name&quot; formControlName=&quot;name&quot;&gt;<br>  &lt;/div&gt;<br>  &lt;div&gt;<br>    &lt;label for=&quot;email&quot;&gt;Email:&lt;/label&gt;<br>    &lt;input type=&quot;email&quot; id=&quot;email&quot; formControlName=&quot;email&quot;&gt;<br>  &lt;/div&gt;<br>  &lt;div&gt;<br>    &lt;label for=&quot;password&quot;&gt;Password:&lt;/label&gt;<br>    &lt;input type=&quot;password&quot; id=&quot;password&quot; formControlName=&quot;password&quot;&gt;<br>  &lt;/div&gt;<br>  &lt;button type=&quot;submit&quot; [disabled]=&quot;profileForm.invalid&quot;&gt;Save&lt;/button&gt;<br>&lt;/form&gt;</pre><h4>Explanation:</h4><ul><li>In the component’s ngOnInit(), form controls for profileImage, name, email, and password are initialized using the formBuilder.group() method.</li><li>formControlName in the HTML template binds form controls to their respective inputs, connecting them with the form group created in the component.</li><li>Validators are applied to enforce specific rules for each form field (e.g., required fields, email format, minimum password length).</li></ul><h3>Step 5: Form Submission Handling and File Input Change</h3><p>To handle form submission and capture changes in the file input for the profile image.</p><p><strong>Handle Form Submission in the Component:</strong></p><pre>onSubmit() {<br>  if (this.profileForm.valid) {<br>    // Process form data (e.g., send to backend)<br>    console.log(this.profileForm.value);<br>  } else {<br>    // Handle form validation errors<br>    console.log(&#39;Form is invalid&#39;);<br>  }<br>}</pre><p>This onSubmit() method logs the form data if the form is valid. You can modify this to perform actions like updating the user profile on the server.</p><p><strong>Handle File Input Changes:</strong></p><pre>onFileChange(event: any) {<br>  const file = event.target.files[0];<br>  if (file) {<br>    this.profileForm.patchValue({<br>      profileImage: file<br>    });<br>  }<br>}</pre><p>This onFileChange() method captures the file selection in the input and updates the profileImage form control.</p><p><strong>Update the HTML Template for File Input:</strong></p><p>Update the file input element in profile-edit.component.html to trigger the onFileChange() method:</p><pre>&lt;input type=&quot;file&quot; id=&quot;profileImage&quot; (change)=&quot;onFileChange($event)&quot; formControlName=&quot;profileImage&quot;&gt;</pre><h4>Explanation:</h4><ul><li>The onSubmit() method checks if the form is valid and logs the form data (simulated by printing to the console). You can extend this method to perform actions like updating user data on a server.</li><li>onFileChange() captures the file input changes and updates the profileImage form control with the selected file.</li></ul><h3>Step 6: Previewing Selected Image</h3><p>To enable users to preview the selected image before submitting the form.</p><p><strong>Add Image Preview Functionality:</strong></p><pre>previewImage(file: File) {<br>  const reader = new FileReader();<br>  reader.readAsDataURL(file);<br>  reader.onload = () =&gt; {<br>    this.imagePreview = reader.result as string;<br>  };<br>}</pre><p>This previewImage() method uses FileReader to read the selected file as a data URL, enabling preview functionality.</p><p><strong>Update the </strong><strong>onFileChange() Method:</strong></p><p>Modify the onFileChange() method to include the image preview:</p><pre>onFileChange(event: any) {<br>  const file = event.target.files[0];<br>  if (file) {<br>    this.profileForm.patchValue({<br>      profileImage: file<br>    });<br>    this.previewImage(file); // Preview the selected image<br>  }<br>}</pre><p><strong>Update HTML Template for Image Preview:</strong></p><p>Update the HTML template to display the selected image preview:</p><pre>&lt;div&gt;<br>  &lt;label for=&quot;profileImage&quot;&gt;Profile Image:&lt;/label&gt;<br>  &lt;input type=&quot;file&quot; id=&quot;profileImage&quot; (change)=&quot;onFileChange($event)&quot; formControlName=&quot;profileImage&quot;&gt;<br>  &lt;img [src]=&quot;imagePreview&quot; *ngIf=&quot;imagePreview&quot; alt=&quot;Profile Image Preview&quot;&gt;<br>&lt;/div&gt;</pre><h4>Explanation:</h4><ul><li>The previewImage() method reads the selected file using FileReader and sets the resulting data URL as imagePreview.</li><li>onFileChange() triggers previewImage() when a file is selected, updating the imagePreview variable with the selected image URL.</li><li>The HTML template includes an &lt;img&gt; tag that binds to imagePreview, displaying the selected image preview if available.</li></ul><h3>Step 7: UI Improvements and Error Handling</h3><p>To display error messages for invalid form fields and improve the visual representation of the form.</p><p><strong>Display Error Messages in the HTML Template:</strong></p><p>Update the HTML template (profile-edit.component.html) to display error messages for invalid fields:</p><pre>&lt;form [formGroup]=&quot;profileForm&quot; (ngSubmit)=&quot;onSubmit()&quot;&gt;<br>  &lt;!-- ... Other form controls ... --&gt;<br><br>  &lt;!-- Display error message for &#39;name&#39; field --&gt;<br>  &lt;div *ngIf=&quot;profileForm.get(&#39;name&#39;).invalid &amp;&amp; profileForm.get(&#39;name&#39;).touched&quot;&gt;<br>    &lt;small *ngIf=&quot;profileForm.get(&#39;name&#39;).errors?.required&quot;&gt;Name is required&lt;/small&gt;<br>  &lt;/div&gt;<br><br>  &lt;!-- Display error message for &#39;email&#39; field --&gt;<br>  &lt;div *ngIf=&quot;profileForm.get(&#39;email&#39;).invalid &amp;&amp; profileForm.get(&#39;email&#39;).touched&quot;&gt;<br>    &lt;small *ngIf=&quot;profileForm.get(&#39;email&#39;).errors?.required&quot;&gt;Email is required&lt;/small&gt;<br>    &lt;small *ngIf=&quot;profileForm.get(&#39;email&#39;).errors?.email&quot;&gt;Invalid email format&lt;/small&gt;<br>  &lt;/div&gt;<br><br>  &lt;!-- Display error message for &#39;password&#39; field --&gt;<br>  &lt;div *ngIf=&quot;profileForm.get(&#39;password&#39;).invalid &amp;&amp; profileForm.get(&#39;password&#39;).touched&quot;&gt;<br>    &lt;small *ngIf=&quot;profileForm.get(&#39;password&#39;).errors?.minlength&quot;&gt;Password must be at least 6 characters&lt;/small&gt;<br>  &lt;/div&gt;<br><br>  &lt;!-- Submit button --&gt;<br>  &lt;button type=&quot;submit&quot; [disabled]=&quot;profileForm.invalid&quot;&gt;Save&lt;/button&gt;<br>&lt;/form&gt;</pre><p><strong>Style the Form for Visual Representation:</strong></p><p>Apply CSS styles to highlight invalid form fields or display error messages more prominently:</p><pre>/* Add styles to highlight invalid fields */<br>input.ng-invalid {<br>  border-color: red;<br>}<br><br>/* Style error messages */<br>small {<br>  color: red;<br>}</pre><h4>Explanation:</h4><ul><li>In the HTML template, error messages are displayed conditionally using Angular’s *ngIf directive based on the validity state and touch status of each form field.</li><li>CSS styles are applied to highlight invalid fields with a red border and style the error messages in red for better visibility.</li></ul><h3>Conclusion:</h3><p>As you conclude your journey with the User Profile Editor, you’ve explored Angular’s power in creating interactive profile editing. You’ve practiced real-time image previews, dynamic form validations, and gained insights into crafting user-friendly interfaces. Now equipped with these skills, you’re ready to create engaging applications with confidence.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19119edf1eec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reactive Forms — Updating parts of the data model]]></title>
            <link>https://medium.com/@hish.abdelshafouk/reactive-forms-updating-parts-of-the-data-model-5ed442ff867f?source=rss-6a9f12465ba7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ed442ff867f</guid>
            <category><![CDATA[form-controls]]></category>
            <category><![CDATA[reactive-forms]]></category>
            <category><![CDATA[formgroup]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[hisham abd elshafouk]]></dc:creator>
            <pubDate>Sat, 25 Nov 2023 22:34:45 GMT</pubDate>
            <atom:updated>2023-11-25T22:34:45.916Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mRzdcQJrIwh36nvJ" /><figcaption>Photo by <a href="https://unsplash.com/@kellysikkema?utm_source=medium&amp;utm_medium=referral">Kelly Sikkema</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Reactive Forms — Updating parts of the data model</h3><p>Navigating between setValue() and patchValue() in Angular Reactive Forms mirrors choosing between a complete overhaul or a surgical update for your form controls. setValue() demands a comprehensive data package, ensuring strict adherence to form structure, while patchValue() offers a precision tool, allowing surgical updates without rigid structural constraints. These methods grant control over your forms, enabling tailored updates tailored to your data needs.</p><h3>setValue()</h3><ul><li><strong>Purpose:</strong> Sets a new value for an individual control within a form group.</li><li><strong>Behavior:</strong> Strictly adheres to the structure of the form group and replaces the entire value for the control.</li><li><strong>Usage:</strong> Useful when you have complete data matching the form structure and want to set values for all controls within the form group.</li></ul><h3>patchValue()</h3><ul><li><strong>Purpose:</strong> Replaces any properties defined in the object that have changed in the form model.</li><li><strong>Behavior:</strong> Updates only the properties present in the provided object without strictly enforcing the form structure.</li><li><strong>Usage:</strong> Useful when updating specific controls or when not all form controls need to be updated.</li></ul><h3>Real-World Scenario:</h3><p>Consider a user profile form with various fields like name, email, and age:</p><pre>this.profileForm = this.formBuilder.group({<br>  name: [&#39;&#39;, Validators.required],<br>  email: [&#39;&#39;, Validators.email],<br>  age: [null, Validators.min(18)]<br>});</pre><h4>setValue() Example:</h4><p>Suppose a user wants to update their entire profile information, including name, email, and age. Using setValue():</p><pre>this.profileForm.setValue({<br>  name: &#39;John Doe&#39;,<br>  email: &#39;john@example.com&#39;,<br>  age: 30<br>});</pre><p>In this scenario, setValue() is appropriate as the user provides all the necessary information, adhering to the structure of the form. If any field is missing or extra fields are included, setValue() will throw an error.</p><h4>patchValue() Example:</h4><p>Imagine the user only wants to update their email address without altering the name or age. Using patchValue():</p><pre>this.profileForm.patchValue({<br>  email: &#39;newemail@example.com&#39;<br>});</pre><p>Here, patchValue() allows updating only the specified field (email) without affecting the other fields. It silently ignores extra fields and doesn&#39;t throw errors if the structure doesn&#39;t exactly match the form.</p><h3>Key Points of Difference:</h3><ul><li><strong>setValue():</strong> Requires a complete object with all fields, strictly adhering to the form structure. It ensures data integrity and throws errors on structural mismatches.</li><li><strong>patchValue():</strong> Allows partial updates by updating specified fields, ignoring extra fields, and doesn&#39;t strictly enforce the form structure. It&#39;s ideal for making partial updates without affecting the entire form or throwing errors due to structural differences.</li></ul><h3>Conclusion:</h3><p>setValue() and patchValue() in Angular Reactive Forms offer different approaches to updating form controls. setValue() is strict and requires complete data, while patchValue() is flexible, allowing partial updates without enforcing the entire structure, enabling more granular control over form updates based on specific needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ed442ff867f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[@HostBinding and @HostListener decorators in Angular]]></title>
            <link>https://medium.com/@hish.abdelshafouk/hostbinding-and-hostlistener-decorators-in-angular-c7633c210f78?source=rss-6a9f12465ba7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7633c210f78</guid>
            <category><![CDATA[hostbinding]]></category>
            <category><![CDATA[hostlistener]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[data-bind]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[hisham abd elshafouk]]></dc:creator>
            <pubDate>Sat, 25 Nov 2023 18:07:23 GMT</pubDate>
            <atom:updated>2023-11-25T18:07:23.677Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8Ulc76CUMu064nPE" /><figcaption>Photo by <a href="https://unsplash.com/@cortes?utm_source=medium&amp;utm_medium=referral">Dennis Cortés</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>@HostBinding and @HostListener decorators in Angular empower components and directives to dynamically bind host element properties and listen for events. @HostBinding links component properties to the host, while @HostListener enables event handling on the host, fostering versatile interactivity and styling in Angular applications.</p><h3>@HostBinding:</h3><h4>Overview:</h4><ul><li><strong>Purpose:</strong> Used to bind a property of the host element (the element to which the directive/component is attached) to a class property.</li><li><strong>Binding Target:</strong> The host element’s properties or attributes.</li><li><strong>Decorator Placement:</strong> Applied to a property within the directive or component class.</li></ul><h4>Real-World Use Case:</h4><p>Consider a scenario where you want to dynamically change the background color of the host element based on a component property.</p><pre>import { Directive, HostBinding, Input } from &#39;@angular/core&#39;;<br><br>@Directive({<br>  selector: &#39;[appHighlight]&#39;<br>})<br>export class HighlightDirective {<br>  @Input() highlightColor: string = &#39;yellow&#39;;<br><br>  @HostBinding(&#39;style.backgroundColor&#39;) backgroundColor: string;<br><br>  ngOnChanges() {<br>    this.backgroundColor = this.highlightColor;<br>  }<br>}</pre><p>In this example, @HostBinding is used to bind the backgroundColor style property of the host element to the highlightColor property of the directive. Whenever the highlightColor input changes, the host element&#39;s background color dynamically updates.</p><h3>@HostListener:</h3><h4>Overview:</h4><ul><li><strong>Purpose:</strong> Used to listen for events on the host element and trigger a method in response.</li><li><strong>Event Target:</strong> The host element to which the directive or component is attached.</li><li><strong>Decorator Placement:</strong> Applied to a method within the directive or component class.</li></ul><h4>Real-World Use Case:</h4><p>Imagine a scenario where you need to handle a click event on the host element and perform an action when it occurs.</p><pre>import { Directive, HostListener } from &#39;@angular/core&#39;;<br><br>@Directive({<br>  selector: &#39;[appClickHandler]&#39;<br>})<br>export class ClickHandlerDirective {<br>  @HostListener(&#39;click&#39;, [&#39;$event&#39;]) onClick(event: Event) {<br>    console.log(&#39;Click event triggered:&#39;, event);<br>    // Perform some action on click<br>  }<br>}</pre><p>In this example, @HostListener is used to listen for a click event on the host element and trigger the onClick() method whenever a click event occurs. This allows you to perform actions or execute logic when the host element is clicked.</p><p>In summary, @HostBinding is used to bind properties of the host element, while @HostListener is used to listen for events on the host element, enabling interaction and manipulation of the host within Angular directives or components.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7633c210f78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[@ViewChild and @ContentChild in Angular]]></title>
            <link>https://medium.com/@hish.abdelshafouk/viewchild-and-contentchild-in-angular-57bd48e3e835?source=rss-6a9f12465ba7------2</link>
            <guid isPermaLink="false">https://medium.com/p/57bd48e3e835</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[viewchild]]></category>
            <category><![CDATA[contentchild]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[hisham abd elshafouk]]></dc:creator>
            <pubDate>Sat, 25 Nov 2023 17:42:38 GMT</pubDate>
            <atom:updated>2023-11-25T17:42:38.246Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0nfHmfnRxweBLFGE" /><figcaption>Photo by <a href="https://unsplash.com/@sonance?utm_source=medium&amp;utm_medium=referral">Viktor Forgacs</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>@ViewChild and @ContentChild in Angular offer powerful means to interact with components and projected content. @ViewChild accesses elements, components, or directives within a component&#39;s template, while @ContentChild retrieves projected elements from a parent component into a child using &lt;ng-content&gt;. These decorators facilitate seamless communication and manipulation between components, enabling versatile Angular applications.</p><h3>@ViewChild:</h3><h4>Overview:</h4><ul><li><strong>Purpose:</strong> Used to access elements, components, or directives that are defined within the template of the current component.</li><li><strong>Access Target:</strong> Elements or directives declared within the component’s template.</li><li><strong>Decorator Placement:</strong> Applied to a property within the component class.</li></ul><h4>Real-World Use Case:</h4><p>Consider a scenario where a parent component needs to access a child component’s method or properties.</p><pre>@Component({<br>  selector: &#39;app-parent&#39;,<br>  template: &#39;&lt;app-child #childRef&gt;&lt;/app-child&gt;&#39;<br>})<br>export class ParentComponent {<br>  @ViewChild(&#39;childRef&#39;) childComponent: ChildComponent;<br><br>  ngAfterViewInit() {<br>    this.childComponent.doSomething();<br>  }<br>}</pre><p>In this example, @ViewChild is used to access the ChildComponent instance declared within the ParentComponent&#39;s template. It allows the parent component to call methods or access properties of the child component after the view has been initialized.</p><h3>@ContentChild:</h3><h4>Overview:</h4><ul><li><strong>Purpose:</strong> Used to access elements, components, or directives projected into the component using &lt;ng-content&gt;.</li><li><strong>Access Target:</strong> Elements or directives projected into the component from its parent component.</li><li><strong>Decorator Placement:</strong> Applied to a property within the component class.</li></ul><h4>Real-World Use Case:</h4><p>Imagine a scenario where a parent component projects content into a child component, and the child component needs to access that projected content.</p><pre>@Component({<br>  selector: &#39;app-parent&#39;,<br>  template: &#39;&lt;app-child&gt;&lt;p #projectedContent&gt;Hello, projected content!&lt;/p&gt;&lt;/app-child&gt;&#39;<br>})<br>export class ParentComponent {}<br><br>@Component({<br>  selector: &#39;app-child&#39;,<br>  template: &#39;&lt;ng-content&gt;&lt;/ng-content&gt;&#39;<br>})<br>export class ChildComponent {<br>  @ContentChild(&#39;projectedContent&#39;) projectedContent: ElementRef;<br><br>  ngAfterContentInit() {<br>    console.log(this.projectedContent.nativeElement.textContent);<br>  }<br>}</pre><p>Here, @ContentChild is used in ChildComponent to access the projected content from the parent component. It allows the child component to manipulate or access the projected content after the content has been initialized.</p><p>In summary, @ViewChild is for accessing elements or components within the current component&#39;s template, while @ContentChild is for accessing projected elements or components from a parent component into the child component using &lt;ng-content&gt;. These decorators facilitate communication and interaction between parent and child components in Angular applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57bd48e3e835" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[forRoot vs forChild — Angular]]></title>
            <link>https://medium.com/@hish.abdelshafouk/forroot-vs-forchild-angular-68ad5d39a481?source=rss-6a9f12465ba7------2</link>
            <guid isPermaLink="false">https://medium.com/p/68ad5d39a481</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[modules]]></category>
            <dc:creator><![CDATA[hisham abd elshafouk]]></dc:creator>
            <pubDate>Sat, 25 Nov 2023 13:53:05 GMT</pubDate>
            <atom:updated>2023-11-25T13:55:10.339Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zaE6RJ0pKOdWiWxf" /><figcaption>Photo by <a href="https://unsplash.com/@kelli_mcclintock?utm_source=medium&amp;utm_medium=referral">Kelli McClintock</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Angular — forRoot vs forChild</h3><p>In Angular, forRoot and forChild are methods used when creating and configuring modules with providers. These methods are commonly used in Angular&#39;s routing and feature modules to set up and configure services or features within the application.</p><h3>forRoot</h3><ul><li><strong>Purpose:</strong> Used in the root AppModule to configure a module and its services that need to be singleton instances shared throughout the application.</li><li><strong>Usage:</strong> Typically used in the main AppModule to configure the root level services or feature modules that are used globally.</li><li><strong>Example:</strong> Configuring services like RouterModule.forRoot() to set up routing in the root module.</li></ul><h3>forChild</h3><ul><li><strong>Purpose:</strong> Used in feature modules or lazy-loaded modules to configure a module without creating a new instance of the provided services.</li><li><strong>Usage:</strong> Applied within feature modules that should not create new instances of services but instead use the singleton instances provided at the root level.</li><li><strong>Example:</strong> Using RouterModule.forChild() within feature modules to define routes without creating a new router instance.</li></ul><h3>Key Differences:</h3><p><strong>Singleton Creation:</strong></p><ul><li>forRoot creates singleton instances of services that are available application-wide.</li><li>forChild uses the already configured instances created by forRoot and doesn&#39;t create new ones.</li></ul><p><strong>Application Scope:</strong></p><ul><li>forRoot is used in the root module and configures services or features for the entire application.</li><li>forChild is applied in feature modules and configures the provided services or features for specific parts of the application.</li></ul><p><strong>Service Instance:</strong></p><ul><li>forRoot creates and provides the initial instance of a service.</li><li>forChild reuses the instances provided by forRoot, ensuring consistency and avoiding re-creation.</li></ul><h4>Example:</h4><pre>// In AppModule<br>@NgModule({<br>  imports: [<br>    SomeModule.forRoot(), // Configuration at root level<br>    RouterModule.forRoot(routes),<br>  ],<br>})<br>export class AppModule {}<br><br>// In FeatureModule<br>@NgModule({<br>  imports: [<br>    SomeModule.forChild(), // Uses existing configurations, doesn&#39;t create new instances<br>    RouterModule.forChild(featureRoutes),<br>  ],<br>})<br>export class FeatureModule {}</pre><p>These methods (forRoot and forChild) offer a way to configure modules and their services differently based on where they are used within the Angular application, ensuring proper scoping and service instance management.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68ad5d39a481" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Route Guards in Angular]]></title>
            <link>https://medium.com/@hish.abdelshafouk/route-guards-in-angular-c9da0d815ef4?source=rss-6a9f12465ba7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9da0d815ef4</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[candeactive]]></category>
            <category><![CDATA[angular-guards]]></category>
            <category><![CDATA[canactivate]]></category>
            <category><![CDATA[route]]></category>
            <dc:creator><![CDATA[hisham abd elshafouk]]></dc:creator>
            <pubDate>Mon, 20 Nov 2023 09:11:44 GMT</pubDate>
            <atom:updated>2023-11-20T09:11:44.262Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p0urRYKyBuNGFIPI" /><figcaption>Photo by <a href="https://unsplash.com/@nickeedoo?utm_source=medium&amp;utm_medium=referral">Nick Tiemeyer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In Angular, guards are special classes used to control and manage access to different parts of an application. They decide whether a user can navigate to a particular route or perform certain actions based on specific conditions, like checking if the user is logged in or has the necessary permissions. Guards act as gatekeepers, allowing or preventing access to different parts of the application, ensuring security and controlling the flow of navigation within the app.</p><h3>Types of Route Guards in Angular:</h3><h4>CanActivate:</h4><ul><li>Determines if a route can be activated and allows navigation based on certain conditions.</li><li>Implemented using CanActivate interface.</li></ul><h4>Use Case — Authentication Guard:</h4><p>Let’s say you have an application with a dashboard page that should only be accessible to authenticated users. The CanActivate guard ensures that only authenticated users can access this page, redirecting unauthenticated users to the login page.</p><p>AuthGuard Service:</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { CanActivate, Router } from &#39;@angular/router&#39;;<br>import { AuthService } from &#39;./auth.service&#39;;<br><br>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class AuthGuard implements CanActivate {<br><br>  constructor(private authService: AuthService, private router: Router) {}<br><br>  canActivate(): boolean {<br>    if (this.authService.isAuthenticated()) {<br>      return true; // Allow access if the user is authenticated<br>    } else {<br>      this.router.navigate([&#39;/login&#39;]); // Redirect to login if not authenticated<br>      return false; // Prevent access to the route<br>    }<br>  }<br>}</pre><p>Route Configuration:</p><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { Routes, RouterModule } from &#39;@angular/router&#39;;<br>import { DashboardComponent } from &#39;./dashboard.component&#39;;<br>import { AuthGuard } from &#39;./auth.guard&#39;;<br><br>const routes: Routes = [<br>  {<br>    path: &#39;dashboard&#39;,<br>    component: DashboardComponent,<br>    canActivate: [AuthGuard] // Apply the AuthGuard to protect the dashboard route<br>  },<br>  // Other route configurations<br>];<br><br>@NgModule({<br>  imports: [RouterModule.forRoot(routes)],<br>  exports: [RouterModule]<br>})<br>export class AppRoutingModule { }</pre><p>AuthService:</p><p>This assumes there’s an AuthService that provides a method isAuthenticated() to check if the user is logged in.</p><h4>CanActivateChild:</h4><ul><li>Similar to CanActivate but controls the activation of child routes.</li><li>Implemented using CanActivateChild interface.</li></ul><h4>Use Case — Admin Panel Access:</h4><p>Imagine an admin panel within an application containing multiple child routes that should only be accessible to authenticated administrators.</p><p>AuthGuard Service:</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { CanActivateChild, Router } from &#39;@angular/router&#39;;<br>import { AuthService } from &#39;./auth.service&#39;;<br><br>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class AdminAuthGuard implements CanActivateChild {<br><br>  constructor(private authService: AuthService, private router: Router) {}<br><br>  canActivateChild(): boolean {<br>    if (this.authService.isUserLoggedIn() &amp;&amp; this.authService.isAdmin()) {<br>      return true; // Allow access if the user is logged in and is an admin<br>    } else {<br>      this.router.navigate([&#39;/unauthorized&#39;]); // Redirect if not authorized<br>      return false; // Prevent access to admin child routes<br>    }<br>  }<br>}</pre><p>Route Configuration:</p><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { Routes, RouterModule } from &#39;@angular/router&#39;;<br>import { AdminPanelComponent } from &#39;./admin-panel.component&#39;;<br>import { AdminAuthGuard } from &#39;./admin-auth.guard&#39;;<br><br>const routes: Routes = [<br>  {<br>    path: &#39;admin&#39;,<br>    component: AdminPanelComponent,<br>    canActivateChild: [AdminAuthGuard], // Apply AdminAuthGuard to protect child routes<br>    children: [<br>      // Child routes accessible only to authenticated admins<br>      // Example: /admin/users, /admin/settings, etc.<br>    ]<br>  },<br>  // Other route configurations<br>];<br><br>@NgModule({<br>  imports: [RouterModule.forRoot(routes)],<br>  exports: [RouterModule]<br>})<br>export class AppRoutingModule { }</pre><h4>CanDeactivate:</h4><ul><li>Checks if a route can be deactivated, often used to confirm navigation away from a route.</li><li>Implemented using CanDeactivate interface.</li></ul><h4>Use Case — Preventing Unsaved Changes:</h4><p>Consider a form-editing feature within an application where users can modify certain data. You want to ensure that users are prompted with a confirmation before leaving the editing page if they’ve made changes that haven’t been saved.</p><p>Deactivation Guard Service:</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { CanDeactivate } from &#39;@angular/router&#39;;<br>import { Observable } from &#39;rxjs&#39;;<br>import { EditComponent } from &#39;./edit.component&#39;;<br><br>export interface CanComponentDeactivate {<br>  canDeactivate: () =&gt; Observable&lt;boolean&gt; | Promise&lt;boolean&gt; | boolean;<br>}<br><br>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class PreventUnsavedChangesGuard implements CanDeactivate&lt;CanComponentDeactivate&gt; {<br><br>  canDeactivate(component: CanComponentDeactivate): Observable&lt;boolean&gt; | Promise&lt;boolean&gt; | boolean {<br>    return component.canDeactivate ? component.canDeactivate() : true;<br>  }<br>}</pre><p>Component Implementation:</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { CanComponentDeactivate } from &#39;./prevent-unsaved-changes.guard&#39;;<br><br>@Component({<br>  selector: &#39;app-edit&#39;,<br>  template: `<br>    &lt;!-- Your edit form --&gt;<br>  `<br>})<br>export class EditComponent implements CanComponentDeactivate {<br><br>  // Track if changes are made to the form<br>  hasUnsavedChanges = false;<br><br>  // Method to check if there are unsaved changes<br>  canDeactivate(): boolean {<br>    if (this.hasUnsavedChanges) {<br>      return confirm(&#39;You have unsaved changes. Are you sure you want to leave?&#39;);<br>    }<br>    return true;<br>  }<br>}</pre><h4>CanLoad:</h4><ul><li>Prevents a module from being loaded lazily until certain conditions are met.</li><li>Implemented using CanLoad interface.</li></ul><h4>Use Case — Role-Based Module Loading:</h4><p>Consider a scenario where your application has a premium feature module that should only be loaded for users with a specific subscription or premium status.</p><p>CanLoad Guard Service:</p><pre>import { Injectable } from &#39;@angular/core&#39;;<br>import { CanLoad, Route, UrlSegment } from &#39;@angular/router&#39;;<br>import { AuthService } from &#39;./auth.service&#39;;<br><br>@Injectable({<br>  providedIn: &#39;root&#39;<br>})<br>export class PremiumFeatureGuard implements CanLoad {<br><br>  constructor(private authService: AuthService) {}<br><br>  canLoad(route: Route, segments: UrlSegment[]): boolean {<br>    if (this.authService.isUserPremium()) {<br>      return true; // Allow lazy loading if the user is premium<br>    } else {<br>      // Handle cases where the user is not premium (redirect, show message, etc.)<br>      return false; // Prevent lazy loading of the premium feature module<br>    }<br>  }<br>}</pre><p>Lazy Loaded Module Configuration:</p><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { RouterModule, Routes } from &#39;@angular/router&#39;;<br>import { PremiumFeatureGuard } from &#39;./premium-feature.guard&#39;;<br><br>const routes: Routes = [<br>  {<br>    path: &#39;premium&#39;,<br>    canLoad: [PremiumFeatureGuard], // Apply PremiumFeatureGuard to prevent lazy loading<br>    loadChildren: () =&gt; import(&#39;./premium-feature/premium-feature.module&#39;).then(m =&gt; m.PremiumFeatureModule)<br>  },<br>  // Other route configurations<br>];<br><br>@NgModule({<br>  imports: [RouterModule.forRoot(routes)],<br>  exports: [RouterModule]<br>})<br>export class AppRoutingModule { }</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9da0d815ef4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Custom Input Component with Form Validation in Angular]]></title>
            <link>https://medium.com/@hish.abdelshafouk/building-a-custom-input-component-with-form-validation-in-angular-fa3f93d5363e?source=rss-6a9f12465ba7------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa3f93d5363e</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[components]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-forms]]></category>
            <dc:creator><![CDATA[hisham abd elshafouk]]></dc:creator>
            <pubDate>Sat, 18 Nov 2023 07:20:55 GMT</pubDate>
            <atom:updated>2023-11-18T07:24:42.108Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*exIIisN7uByKzO9v" /><figcaption>Photo by <a href="https://unsplash.com/@honeypoppet?utm_source=medium&amp;utm_medium=referral">Sandie Clarke</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Creating reusable and validated form components is pivotal in modern web development. In this journey of Angular exploration, we’ve crafted a versatile Custom Input Component designed to handle various input types and facilitate form validation seamlessly within Angular applications.</p><h3>1. Setting Up the Angular Project:</h3><p><strong>Create a New Angular Project</strong>:</p><pre>ng new custom-input-project</pre><p><strong>Generate the Custom Input Component</strong>:</p><pre>ng generate component custom-input</pre><h4>Directory Structure:</h4><pre>custom-input-project/<br>├── src/<br>│ ├── app/<br>│ │ ├── custom-input/<br>│ │ │ ├── custom-input.component.html<br>│ │ │ ├── custom-input.component.css<br>│ │ │ ├── custom-input.component.spec.ts<br>│ │ │ └── custom-input.component.ts<br>│ │ ├── app.component.html<br>│ │ ├── app.component.css<br>│ │ ├── app.component.spec.ts<br>│ │ └── app.component.ts<br>│ │ ├── app.module.ts<br>│ │ └── …<br>│ └── …<br>└── …</pre><h3>2. Creating the Custom Input Component:</h3><p>The CustomInputComponent will encapsulate the input field, handle different input types, and implement basic form validation using Angular&#39;s FormControl and Validators.</p><h4>Component Structure (custom-input.component.ts):</h4><p>The CustomInputComponent TypeScript file (custom-input.component.ts):</p><pre>import { Component, Input, Output, EventEmitter } from &#39;@angular/core&#39;;<br>import { FormControl, Validators } from &#39;@angular/forms&#39;;<br><br>@Component({<br>  selector: &#39;app-custom-input&#39;,<br>  templateUrl: &#39;./custom-input.component.html&#39;,<br>  styleUrls: [&#39;./custom-input.component.css&#39;]<br>})<br>export class CustomInputComponent {<br>  @Input() label: string = &#39;&#39;;<br>  @Input() type: string = &#39;text&#39;;<br>  @Output() valueChange = new EventEmitter&lt;string&gt;();<br><br>  control: FormControl = new FormControl(&#39;&#39;, Validators.required);<br><br>  get value(): string {<br>    return this.control.value;<br>  }<br><br>  set value(val: string) {<br>    this.control.setValue(val);<br>    this.valueChange.emit(val);<br>  }<br>}</pre><p>Component Template (custom-input.component.html):</p><p>The CustomInputComponent HTML template (custom-input.component.html):</p><pre>&lt;div class=&quot;form-group&quot;&gt;<br>  &lt;label&gt;{{ label }}&lt;/label&gt;<br>  &lt;input<br>    [type]=&quot;type&quot;<br>    class=&quot;form-control&quot;<br>    [formControl]=&quot;control&quot;<br>    [attr.placeholder]=&quot;label&quot;<br>  /&gt;<br>  &lt;div *ngIf=&quot;control.invalid &amp;&amp; control.touched&quot; class=&quot;text-danger&quot;&gt;<br>    This field is required.<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><h4>Explanation:</h4><ul><li>The CustomInputComponent TypeScript file defines the component&#39;s logic.</li><li>It uses @Input to receive label and type properties, and @Output to emit value changes.</li><li>FormControl is utilized for form handling, including basic validation (in this case, it&#39;s required).</li><li>The template renders the input field and displays a validation message for required fields.</li><li>Component styles can be customized as needed for UI adjustments.</li></ul><h3>3. Utilizing the Custom Input in a Form:</h3><p>Integrating the CustomInputComponent within a reactive form demonstrates how it functions within an Angular form environment.</p><p>Component’s Parent (app.component.ts):</p><pre>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { FormBuilder, FormGroup } from &#39;@angular/forms&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  templateUrl: &#39;./app.component.html&#39;,<br>  styleUrls: [&#39;./app.component.css&#39;],<br>})<br>export class AppComponent implements OnInit {<br>  form: FormGroup;<br><br>  constructor(private fb: FormBuilder) {}<br><br>  ngOnInit() {<br>    this.form = this.fb.group({<br>      name: [&#39;&#39;, Validators.required],<br>    });<br>  }<br>}</pre><p>Parent Component’s Template (app.component.html):</p><pre>&lt;form [formGroup]=&quot;form&quot;&gt;<br>  &lt;app-custom-input<br>    label=&quot;Enter Name&quot;<br>    [type]=&quot;&#39;text&#39;&quot;<br>    formControlName=&quot;name&quot;<br>  &gt;&lt;/app-custom-input&gt;<br>&lt;/form&gt;</pre><h4>Explanation:</h4><ul><li>The AppComponent utilizes the FormBuilder to create a form group and a form control for the input field.</li><li>In the parent component’s template (app.component.html), the CustomInputComponent is used within the form and bound to the form control using formControlName.</li><li>The label and input type are specified as @Input properties of the CustomInputComponent.</li><li>The input field within CustomInputComponent now functions within an Angular reactive form, utilizing form control properties for validation.</li></ul><h3>4. Testing the Custom Input Component:</h3><p>Validating and testing the CustomInputComponent ensures its reliability and functionality across different input types and validation scenarios.</p><p>Component Testing (custom-input.component.spec.ts):</p><pre>import { ComponentFixture, TestBed } from &#39;@angular/core/testing&#39;;<br>import { ReactiveFormsModule, FormGroup, FormBuilder } from &#39;@angular/forms&#39;;<br>import { CustomInputComponent } from &#39;./custom-input.component&#39;;<br><br>describe(&#39;CustomInputComponent&#39;, () =&gt; {<br>  let component: CustomInputComponent;<br>  let fixture: ComponentFixture&lt;CustomInputComponent&gt;;<br>  let formBuilder: FormBuilder;<br><br>  beforeEach(async () =&gt; {<br>    await TestBed.configureTestingModule({<br>      declarations: [CustomInputComponent],<br>      imports: [ReactiveFormsModule],<br>    }).compileComponents();<br>  });<br><br>  beforeEach(() =&gt; {<br>    fixture = TestBed.createComponent(CustomInputComponent);<br>    component = fixture.componentInstance;<br>    formBuilder = TestBed.inject(FormBuilder);<br>    fixture.detectChanges();<br>  });<br><br>  it(&#39;should create the component&#39;, () =&gt; {<br>    expect(component).toBeTruthy();<br>  });<br><br>  it(&#39;should display the input field&#39;, () =&gt; {<br>    const compiled = fixture.nativeElement;<br>    expect(compiled.querySelector(&#39;input&#39;)).toBeTruthy();<br>  });<br><br>  it(&#39;should validate required field&#39;, () =&gt; {<br>    const control = formBuilder.control(&#39;&#39;, { required: true });<br>    const form = formBuilder.group({ testInput: control });<br><br>    component.control = control;<br>    fixture.detectChanges();<br><br>    expect(form.valid).toBeFalsy();<br><br>    const input = fixture.nativeElement.querySelector(&#39;input&#39;);<br>    input.value = &#39;Test Value&#39;;<br>    input.dispatchEvent(new Event(&#39;input&#39;));<br><br>    fixture.detectChanges();<br>    expect(form.valid).toBeTruthy();<br>  });<br><br>  it(&#39;should render the label&#39;, () =&gt; {<br>    component.label = &#39;Test Label&#39;;<br>    fixture.detectChanges();<br><br>    const compiled = fixture.nativeElement;<br>    expect(compiled.querySelector(&#39;label&#39;).textContent).toContain(&#39;Test Label&#39;);<br>  });<br><br>  // Add more specific tests for different input types, validation, and behavior<br>});</pre><h4>Explanation:</h4><ul><li>The test suite for CustomInputComponent includes multiple tests to validate different aspects of the input component.</li><li>The first test ensures the successful creation of the CustomInputComponent.</li><li>The second test checks if the input field is displayed within the component.</li><li>The third test validates the required field functionality. It creates a form control, assigns it to the component, and simulates user input to check the field’s validation.</li><li>The fourth test verifies the rendering of the label within the component.</li></ul><h3>Conclusion:</h3><p>Through Angular’s capabilities, we’ve built a Custom Input Component that excels in adaptability and reliability. From its inception to rigorous testing, we’ve explored the art of crafting reusable components that enhance form interactions within Angular applications. This journey paves the way to create user-centric experiences through versatile and validated input fields.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa3f93d5363e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Scopes and Closures in JavaScript]]></title>
            <link>https://medium.com/@hish.abdelshafouk/demystifying-scopes-and-closures-in-javascript-269553551acc?source=rss-6a9f12465ba7------2</link>
            <guid isPermaLink="false">https://medium.com/p/269553551acc</guid>
            <category><![CDATA[closure-in-javascript]]></category>
            <category><![CDATA[javascript-scope]]></category>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[closures-functions]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[hisham abd elshafouk]]></dc:creator>
            <pubDate>Fri, 17 Nov 2023 23:24:41 GMT</pubDate>
            <atom:updated>2023-11-17T23:40:03.704Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EBX6ooxWgotXNbgi" /><figcaption>Photo by <a href="https://unsplash.com/@clemono?utm_source=medium&amp;utm_medium=referral">Clem Onojeghuo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Scopes in JavaScript are like invisible boxes that hold our variables. When we write code, these boxes decide where our toys (variables) can be found and played with. Closures, on the other hand, are like secret treasure chests within these boxes that keep memories even when the box is closed.</p><h4><strong>Understanding Scopes:</strong></h4><ul><li><strong>Global Scope</strong>: Think of this as the biggest box that holds all the toys. Whatever toy you put in here, everyone can see and play with it.</li><li><strong>Local Scope</strong>: These are smaller boxes inside the big one. Toys in here can only be seen and played with by the ones inside this box.</li></ul><h4><strong>Relation of Closures to Scopes:</strong></h4><p>Closures are like secret boxes inside the smaller boxes that hold special toys. Even if you take the smaller box out, the special toy inside it remembers where it came from.</p><p><strong>Example: Closure in Action</strong></p><pre>function outerFunction() {<br>  const outerVar = &#39;I am from outer&#39;; // A big box with a hidden toy<br><br>  function innerFunction() {<br>    console.log(outerVar); // A smaller box inside the big one<br>  }<br><br>  return innerFunction; // You take the smaller box out<br>}<br><br>const closure = outerFunction(); // You get a special box named &#39;closure&#39;<br>closure(); // When you open it, you find the hidden toy saying: &#39;I am from outer&#39;</pre><p><strong>Explanation of the Code:</strong></p><ul><li>outerFunction creates a special box that hides another smaller box inside.</li><li>When you open the special box (closure), you find the hidden toy (outerVar).</li><li>This shows how the inner box (innerFunction) remembers its special toy (outerVar) even after the outer box (outerFunction) is closed.</li></ul><h4><strong>Conclusion:</strong></h4><p>Understanding scopes is like knowing where our toys are kept, while closures are the secret chests that hold memories. Knowing this helps us write better and smarter code, keeping things organized and safe.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=269553551acc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>