<?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 Akhil Goyal on Medium]]></title>
        <description><![CDATA[Stories by Akhil Goyal on Medium]]></description>
        <link>https://medium.com/@akhilgoyals?source=rss-19e4cfb47283------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lRAaxQY0-0pRF5dUpLotFA.jpeg</url>
            <title>Stories by Akhil Goyal on Medium</title>
            <link>https://medium.com/@akhilgoyals?source=rss-19e4cfb47283------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 02:42:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@akhilgoyals/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[@ViewChild in Angular]]></title>
            <link>https://medium.com/@akhilgoyals/viewchild-in-angular-84540ab7b573?source=rss-19e4cfb47283------2</link>
            <guid isPermaLink="false">https://medium.com/p/84540ab7b573</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Akhil Goyal]]></dc:creator>
            <pubDate>Sat, 29 Mar 2025 16:25:13 GMT</pubDate>
            <atom:updated>2025-03-29T16:25:13.517Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*37r7cCQP6JvmCdFO3Gd_vg.jpeg" /></figure><p>Hello! If you’re new to Angular and wondering how a parent component can directly interact with its child components or DOM elements, you’re in the right place!</p><p>In this article, we’ll explore the @ViewChild decorator — a powerful tool in Angular that lets you access child components, directives, or DOM elements in your code.</p><p>We’ll use a simple example to show how it works: a parent component focusing an input field in a child component. No fancy styling, just plain Angular to keep the focus on the concepts.</p><h3>What Is @ViewChild?</h3><p>In Angular, components are like building blocks of your app. Sometimes, a parent component needs to reach into its child component or a specific element in its template to do something — like calling a method or changing a property. That’s where @ViewChildcomes in. It’s a decorator that lets the parent component find and interact with a child component, directive, or DOM element directly.</p><p>Think of it like a parent asking a child to do something specific — like telling them to start playing a toy piano. The parent can’t play the piano themselves because it’s in the child’s hands, but they can ask the child to do it. In Angular, @ViewChild is like the parent’s ability to say, “Hey, child, I need you to do this!”</p><h3>Setting Up the Project</h3><p>Let’s set up a minimal Angular project to demonstrate @ViewChild.</p><p>First, create a new project with this command:</p><pre>ng new angular-viewchild-demo<br>cd angular-viewchild-demo</pre><p>We’ll keep it simple — no styling, just plain HTML and Angular. Let’s create a ChildComponent with:</p><pre>ng g c child</pre><p>And set up the routing in app.config.ts:</p><pre>import { ApplicationConfig } from &#39;@angular/core&#39;;<br>import { provideRouter } from &#39;@angular/router&#39;;<br><br>export const appConfig: ApplicationConfig = {<br>  providers: [<br>    provideRouter([<br>      { path: &#39;&#39;, pathMatch: &#39;full&#39;, redirectTo: &#39;&#39; },<br>      { path: &#39;**&#39;, redirectTo: &#39;&#39; }<br>    ])<br>  ]<br>};</pre><p>Now, let’s build our example step by step using @ViewChild to control a Child Component.</p><p>Let’s create an app where a parent component uses @ViewChild to focus an input field in a child component. This is a common use case — like when you want to automatically focus an input field when a user clicks a button.</p><h4>Step 1: Create the Child Component</h4><p>First, let’s set up the ChildComponent with an input field that we can focus.</p><p>Here’s the code for child.component.ts:</p><pre>import { Component, ElementRef, ViewChild } from &#39;@angular/core&#39;;<br>import { FormsModule } from &#39;@angular/forms&#39;;<br><br>@Component({<br>  selector: &#39;app-child&#39;,<br>  standalone: true,<br>  imports: [FormsModule],<br>  template: `<br>    &lt;div&gt;<br>      &lt;h3&gt;Child Component&lt;/h3&gt;<br>      &lt;p&gt;Child Input: &lt;input #childInput type=&quot;text&quot; [(ngModel)]=&quot;inputValue&quot; placeholder=&quot;Type something...&quot;&gt;&lt;/p&gt;<br>    &lt;/div&gt;<br>  `<br>})<br><br>export class ChildComponent {<br>  @ViewChild(&#39;childInput&#39;) childInput!: ElementRef&lt;HTMLInputElement&gt;;<br>  inputValue = &#39;&#39;;<br>  focusInput() {<br>    this.childInput.nativeElement.focus();<br>  }<br>}</pre><p>In this code:</p><ul><li>We have an input field with a template reference variable #childInput.</li><li>We use @ViewChild to access this input element as an ElementRef.</li><li>The focusInput method focuses the input field by calling focus() on the native DOM element.</li></ul><h4>Step 2: Use @ViewChild in the Parent Component</h4><p>Now, let’s set up the AppComponent to use @ViewChild to call the focusInput method on the ChildComponent.</p><p>Here’s the code for app.component.ts:</p><pre>import { Component, ViewChild } from &#39;@angular/core&#39;;<br>import { ChildComponent } from &#39;./child/child.component&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  standalone: true,<br>  imports: [ChildComponent],<br>  template: `<br>    &lt;h1&gt;Angular @ViewChild Demo&lt;/h1&gt;<br>    &lt;button (click)=&quot;focusChildInput()&quot;&gt;Focus Child Input&lt;/button&gt;<br>    &lt;app-child&gt;&lt;/app-child&gt;<br>  `<br>})<br>export class AppComponent {<br>  @ViewChild(ChildComponent) childComponent!: ChildComponent;<br>  focusChildInput() {<br>    this.childComponent.focusInput();<br>  }<br>}</pre><p>In this code:</p><ul><li>We use @ViewChild to get a reference to the ChildComponent.</li><li>When the ‘Focus Child Input’ button is clicked, we call the focusInput method on the child component, which focuses the input field.</li></ul><p>Run the app with npm start. Click the ‘Focus Child Input’ button, and you’ll see the input field in the child component get focused — the cursor will start blinking in the input. This shows how @ViewChild lets the parent component interact with the child component, like telling it to focus the input.</p><h4>Using @ViewChild to Access a DOM Element Directly</h4><p>You can also use @ViewChild to access DOM elements directly in the same component — not just child components. Let’s add an input field to the AppComponent and use @ViewChild to focus it.</p><p>Update app.component.ts:</p><pre>import { Component, ViewChild, ElementRef } from &#39;@angular/core&#39;;<br>import { ChildComponent } from &#39;./child/child.component&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  standalone: true,<br>  imports: [ChildComponent],<br>  template: `<br>    &lt;h1&gt;Angular @ViewChild Demo&lt;/h1&gt;<br>    &lt;p&gt;Parent Input: &lt;input #parentInput type=&quot;text&quot; placeholder=&quot;Type something...&quot;&gt;&lt;/p&gt;<br>    &lt;button (click)=&quot;focusParentInput()&quot;&gt;Focus Parent Input&lt;/button&gt;<br>    &lt;button (click)=&quot;focusChildInput()&quot;&gt;Focus Child Input&lt;/button&gt;<br>    &lt;app-child&gt;&lt;/app-child&gt;<br>  `<br>})<br>export class AppComponent {<br>  @ViewChild(ChildComponent) childComponent!: ChildComponent;<br>  @ViewChild(&#39;parentInput&#39;) parentInput!: ElementRef&lt;HTMLInputElement&gt;;<br>  focusParentInput() {<br>    this.parentInput.nativeElement.focus();<br>  }<br>  focusChildInput() {<br>    this.childComponent.focusInput();<br>  }<br>}</pre><p>In this updated code:</p><ul><li>We added an input field in the AppComponent with a template reference variable #parentInput.</li><li>We use @ViewChild to access this input element directly as an ElementRef.</li><li>The focusParentInput method focuses the parent’s input field.</li></ul><p>Run the app again. Now you have two buttons: one to focus the parent’s input and one to focus the child’s input. Click ‘Focus Parent Input’, and the parent’s input field gets focused. This shows how @ViewChild can be used to access DOM elements directly, not just child components.</p><h4>Best Practices for Using @ViewChild</h4><p>Here are a few tips to use @ViewChild effectively:</p><ol><li><strong>Use Sparingly:</strong> Only use @ViewChild when you need to interact with the DOM or a child component directly. For most interactions, consider using @Input or @Output instead.</li><li><strong>Wait for the View: </strong>Make sure the element or component is available before using it. Use ngAfterViewInit to ensure the view is ready, especially if the element might not be in the DOM yet.</li><li><strong>Be Safe with DOM Access:</strong> When accessing DOM elements, use ElementRef and nativeElement carefully, especially in server-side rendering scenarios where the DOM might not exist.</li><li><strong>Consider Alternatives: </strong>For complex interactions between components, a shared service might be a better choice than @ViewChild.</li></ol><p>Following these tips will help you use @ViewChild effectively and keep your code clean.</p><h3>Wrapping Up</h3><p>We’ve explored how to use Angular’s @ViewChild decorator to let a parent component interact with a child component — like focusing an input field — and how to access DOM elements directly. Here’s a quick recap:</p><ul><li>@ViewChild lets you access child components, like calling a method to focus an input.</li><li>It can also access DOM elements directly, like focusing an input in the same component.</li><li>Use it wisely, and always ensure the view is ready before accessing elements.</li></ul><p>I hope this simple example made @ViewChild easy to understand! Try using it in your own projects — maybe to control a child component’s behaviour or manipulate a DOM element — and see how it works for you.</p><p>If you want to learn more about Angular, check out my new <a href="https://www.youtube.com/channel/UCgzsUfGTn6n5snVdoIO3uNQ">YouTube channel</a> where I share everything I know about Angular &amp; its latest updates.</p><p>Thank you for reading this article. See you in the next one :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84540ab7b573" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refresher: Angular Component Lifecycle Hooks!]]></title>
            <link>https://medium.com/@akhilgoyals/refresher-angular-component-lifecycle-hooks-e62a266a6bbb?source=rss-19e4cfb47283------2</link>
            <guid isPermaLink="false">https://medium.com/p/e62a266a6bbb</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Akhil Goyal]]></dc:creator>
            <pubDate>Fri, 28 Mar 2025 21:23:41 GMT</pubDate>
            <atom:updated>2025-03-28T21:23:41.269Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FBToGjZ1iVljcDPslPDvOA.jpeg" /></figure><p>If you’re new to Angular and wondering what happens behind the scenes when a component is created, updated, or removed, you’re in the right place!</p><p>In this article, we’ll explore Angular Component Lifecycle Hooks — special methods that Angular calls at different stages of a component’s life. We’ll break it down into small, easy-to-digest pieces using a simple counter example, introducing each lifecycle hook one by one.</p><h3>What Are Lifecycle Hooks?</h3><p>When Angular creates a component, it goes through different stages — like being born, growing, and eventually being removed. At each stage, Angular gives you a chance to run your own code using lifecycle hooks. These hooks are methods you can implement in your component to do things like initialize data, react to changes, or clean up resources.</p><p>There are eight main lifecycle hooks, and they happen in this order:</p><ol><li><strong>ngOnChanges:</strong> Runs when an input property changes.</li><li><strong>ngOnInit:</strong> Runs once when the component is first set up.</li><li><strong>ngDoCheck: </strong>Runs every time Angular checks for changes.</li><li><strong>ngAfterContentInit:</strong> Runs once after Angular adds external content.</li><li><strong>ngAfterContentChecked:</strong> Runs after Angular checks the external content.</li><li><strong>ngAfterViewInit:</strong> Runs once after Angular creates the component’s view.</li><li><strong>ngAfterViewChecked: </strong>Runs after Angular checks the view for changes.</li><li><strong>ngOnDestroy: </strong>Runs just before the component is destroyed.</li></ol><p>We’ll use a simple counter component to demonstrate each hook, logging messages to the console to show when they run. Let’s get started by setting up our project!</p><h3>Setting Up the Project</h3><p>First, create a new Angular project with this command:</p><pre>ng new angular-lifecycle-counter-demo<br>cd angular-lifecycle-counter-demo</pre><p>We’ll keep it minimal — no styling, just plain HTML and Angular. Let’s create a CounterComponent with:</p><pre>ng g c counter</pre><p>And set up the routing in app.config.ts:</p><pre>import { ApplicationConfig } from &#39;@angular/core&#39;;<br>import { provideRouter } from &#39;@angular/router&#39;;<br><br>export const appConfig: ApplicationConfig = {<br>  providers: [<br>    provideRouter([<br>      { path: &#39;&#39;, pathMatch: &#39;full&#39;, redirectTo: &#39;&#39; },<br>      { path: &#39;**&#39;, redirectTo: &#39;&#39; }<br>    ])<br>  ]<br>};</pre><p>Now, let’s dive into each lifecycle hook, one at a time, building on the example as we go.</p><h4>1. ngOnChanges: Reacting to Input Changes</h4><p>The first lifecycle hook is ngOnChanges. This hook runs whenever an input property changes — like when a parent component passes new data to the child.</p><p>Let’s create our CounterComponent to display a count value passed from the parent, and log when the input changes. Here’s the code for counter.component.ts:</p><pre>import { Component, Input, OnChanges, SimpleChanges } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-counter&#39;,<br>  standalone: true,<br>  template: `<br>    &lt;p&gt;Counter: {{ count }}&lt;/p&gt;<br>  `<br>})<br>export class CounterComponent implements OnChanges {<br>  @Input() count: number = 0;<br>  ngOnChanges(changes: SimpleChanges) {<br>    console.log(&#39;ngOnChanges: Input changed&#39;, changes);<br>  }<br>}</pre><p>Now, let’s use this in the AppComponent (app.component.ts):</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { FormsModule } from &#39;@angular/forms&#39;;<br>import { CounterComponent } from &#39;./counter/counter.component&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  standalone: true,<br>  imports: [FormsModule, CounterComponent],<br>  template: `<br>    &lt;h1&gt;Angular Lifecycle Hooks: ngOnChanges&lt;/h1&gt;<br>    &lt;p&gt;Initial Count: &lt;input type=&quot;number&quot; [(ngModel)]=&quot;initialCount&quot; (ngModelChange)=&quot;updateCount($event)&quot;&gt;&lt;/p&gt;<br>    &lt;app-counter [count]=&quot;initialCount&quot;&gt;&lt;/app-counter&gt;<br>  `<br>})<br>export class AppComponent {<br>  initialCount = 0;<br>  updateCount(value: number) {<br>    this.initialCount = value;<br>  }<br>}</pre><p>Run the app with npm start and open the browser console. When the app loads, you’ll see ngOnChanges run once because the initial count is set to 0. Now, change the count to 5 in the input field — you’ll see ngOnChanges run again, logging the change from 0 to 5. This shows how ngOnChanges lets you react to input changes.</p><h4>2. ngOnInit: Initializing the Component</h4><p>Next, let’s add ngOnInit. This hook runs once when the component is first set up, after the first ngOnChanges. It’s the perfect place to initialize data.</p><p>Let’s update the CounterComponent to log when it’s initialized. Update counter.component.ts:</p><pre>import { Component, Input, OnChanges, OnInit, SimpleChanges } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-counter&#39;,<br>  standalone: true,<br>  template: `<br>    &lt;p&gt;Counter: {{ count }}&lt;/p&gt;<br>  `<br>})<br>export class CounterComponent implements OnChanges, OnInit {<br><br>  @Input() count: number = 0;<br>  ngOnChanges(changes: SimpleChanges) {<br>    console.log(&#39;ngOnChanges: Input changed&#39;, changes);<br>  }<br><br>  ngOnInit() {<br>    console.log(&#39;ngOnInit: Component initialized with count&#39;, this.count);<br>  }<br>}</pre><p>The AppComponent stays the same. Run the app again. You’ll see ngOnChanges run first, then ngOnInit runs once, logging the initial count. Change the count to 5 — ngOnChanges runs, but ngOnInit doesn’t because it only runs once when the component is created. This shows how ngOnInit is used for one-time setup.</p><h4>3. ngDoCheck: Monitoring Changes</h4><p>Now, let’s add ngDoCheck. This hook runs every time Angular checks for changes, which happens a lot — like when you click a button or type in an input. Let’s add a button to the CounterComponent to increment the count. Update counter.component.ts:</p><pre>import { Component, Input, OnChanges, OnInit, DoCheck, SimpleChanges } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-counter&#39;,<br>  standalone: true,<br>  template: `<br>    &lt;p&gt;Counter: {{ count }}&lt;/p&gt;<br>    &lt;button (click)=&quot;increment()&quot;&gt;Add 1&lt;/button&gt;<br>  `<br>})<br><br>export class CounterComponent implements OnChanges, OnInit, DoCheck {<br><br>  @Input() count: number = 0;<br><br>  ngOnChanges(changes: SimpleChanges) {<br>    console.log(&#39;ngOnChanges: Input changed&#39;, changes);<br>  }<br>  ngOnInit() {<br>    console.log(&#39;ngOnInit: Component initialized with count&#39;, this.count);<br>  }<br>  ngDoCheck() {<br>    console.log(&#39;ngDoCheck: Change detection running, current count&#39;, this.count);<br>  }<br>  increment() {<br>    this.count++;<br>  }<br>}</pre><p>Run the app. You’ll see ngOnChanges and ngOnInit as before, but now ngDoCheck runs every time Angular checks for changes — like when you click the ‘Add 1’ button or change the input. Click the button to increment the count — you’ll see ngDoCheck run each time. This shows how ngDoCheck lets you monitor changes, but be careful — it runs a lot!</p><h4>4. ngAfterContentInit: Setting Up Projected Content</h4><p>Next, let’s add ngAfterContentInit. This hook runs once after Angular adds external content to the component, like content passed with &lt;ng-content&gt;. Let’s add some projected content to the CounterComponent. Update counter.component.ts:</p><pre>import { Component, Input, OnChanges, OnInit, DoCheck, AfterContentInit, SimpleChanges } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-counter&#39;,<br>  standalone: true,<br>  template: `<br>    &lt;p&gt;Counter: {{ count }}&lt;/p&gt;<br>    &lt;button (click)=&quot;increment()&quot;&gt;Add 1&lt;/button&gt;<br>    &lt;ng-content&gt;&lt;/ng-content&gt;<br>  `<br>})<br><br>export class CounterComponent implements OnChanges, OnInit, DoCheck, AfterContentInit {<br>  <br>@Input() count: number = 0;<br><br>  ngOnChanges(changes: SimpleChanges) {<br>    console.log(&#39;ngOnChanges: Input changed&#39;, changes);<br>  }<br>  ngOnInit() {<br>    console.log(&#39;ngOnInit: Component initialized with count&#39;, this.count);<br>  }<br>  ngDoCheck() {<br>    console.log(&#39;ngDoCheck: Change detection running, current count&#39;, this.count);<br>  }<br>  ngAfterContentInit() {<br>    console.log(&#39;ngAfterContentInit: Content projected into component&#39;);<br>  }<br>  increment() {<br>    this.count++;<br>  }<br>}</pre><p>Update the AppComponent to project some content (app.component.ts):</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { FormsModule } from &#39;@angular/forms&#39;;<br>import { CounterComponent } from &#39;./counter/counter.component&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  standalone: true,<br>  imports: [FormsModule, CounterComponent],<br>  template: `<br>    &lt;h1&gt;Angular Lifecycle Hooks: ngAfterContentInit&lt;/h1&gt;<br>    &lt;p&gt;Initial Count: &lt;input type=&quot;number&quot; [(ngModel)]=&quot;initialCount&quot; (ngModelChange)=&quot;updateCount($event)&quot;&gt;&lt;/p&gt;<br>    &lt;app-counter [count]=&quot;initialCount&quot;&gt;<br>      &lt;p&gt;Extra Info: This is a counter!&lt;/p&gt;<br>    &lt;/app-counter&gt;<br>  `<br>})<br><br>export class AppComponent {<br>  initialCount = 0;<br>  updateCount(value: number) {<br>    this.initialCount = value;<br>  }<br>}</pre><p>Run the app. You’ll see ngOnChanges, ngOnInit, and ngDoCheck as before, then ngAfterContentInit runs once after Angular adds the projected content (‘Extra Info: This is a counter!’). This shows how ngAfterContentInit lets you run code after content is added.</p><h4>5. ngAfterContentChecked: Verifying Projected Content</h4><p>Now, let’s add ngAfterContentChecked. This hook runs after Angular checks the projected content for changes, during every change detection cycle. Update counter.component.ts:</p><pre>import { Component, Input, OnChanges, OnInit, DoCheck, AfterContentInit, AfterContentChecked, SimpleChanges } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-counter&#39;,<br>  standalone: true,<br>  template: `<br>    &lt;p&gt;Counter: {{ count }}&lt;/p&gt;<br>    &lt;button (click)=&quot;increment()&quot;&gt;Add 1&lt;/button&gt;<br>    &lt;ng-content&gt;&lt;/ng-content&gt;<br>  `<br>})<br>export class CounterComponent implements OnChanges, OnInit, DoCheck, AfterContentInit, AfterContentChecked {<br>  <br>@Input() count: number = 0;<br>  <br>ngOnChanges(changes: SimpleChanges) {<br>    console.log(&#39;ngOnChanges: Input changed&#39;, changes);<br>  }<br>  ngOnInit() {<br>    console.log(&#39;ngOnInit: Component initialized with count&#39;, this.count);<br>  }<br>  ngDoCheck() {<br>    console.log(&#39;ngDoCheck: Change detection running, current count&#39;, this.count);<br>  }<br>  ngAfterContentInit() {<br>    console.log(&#39;ngAfterContentInit: Content projected into component&#39;);<br>  }<br>  ngAfterContentChecked() {<br>    console.log(&#39;ngAfterContentChecked: Content checked&#39;);<br>  }<br>  increment() {<br>    this.count++;<br>  }<br>}</pre><p>Run the app. You’ll see the previous hooks, then ngAfterContentChecked runs after ngAfterContentInit and during every change detection cycle — like when you click the ‘Add 1’ button. This shows how ngAfterContentChecked lets you verify the projected content after changes.</p><h4>6. ngAfterViewInit: Setting Up the View</h4><p>Next, let’s add ngAfterViewInit. This hook runs once after Angular creates the component’s view, including its template and child components. Update counter.component.ts:</p><pre>import { Component, Input, OnChanges, OnInit, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit, SimpleChanges } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-counter&#39;,<br>  standalone: true,<br>  template: `<br>    &lt;p&gt;Counter: {{ count }}&lt;/p&gt;<br>    &lt;button (click)=&quot;increment()&quot;&gt;Add 1&lt;/button&gt;<br>    &lt;ng-content&gt;&lt;/ng-content&gt;<br>  `<br>})<br>export class CounterComponent implements OnChanges, OnInit, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit {<br>  <br>@Input() count: number = 0;<br> <br> ngOnChanges(changes: SimpleChanges) {<br>    console.log(&#39;ngOnChanges: Input changed&#39;, changes);<br>  }<br>  ngOnInit() {<br>    console.log(&#39;ngOnInit: Component initialized with count&#39;, this.count);<br>  }<br>  ngDoCheck() {<br>    console.log(&#39;ngDoCheck: Change detection running, current count&#39;, this.count);<br>  }<br>  ngAfterContentInit() {<br>    console.log(&#39;ngAfterContentInit: Content projected into component&#39;);<br>  }<br>  ngAfterContentChecked() {<br>    console.log(&#39;ngAfterContentChecked: Content checked&#39;);<br>  }<br>  ngAfterViewInit() {<br>    console.log(&#39;ngAfterViewInit: View initialized&#39;);<br>  }<br>  increment() {<br>    this.count++;<br>  }<br>}</pre><h4>7. ngAfterViewChecked: Verifying the View</h4><p>Now, let’s add ngAfterViewChecked. This hook runs after Angular checks the view for changes, during every change detection cycle. Update counter.component.ts:</p><pre>import { Component, Input, OnChanges, OnInit, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked, SimpleChanges } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-counter&#39;,<br>  standalone: true,<br>  template: `<br>    &lt;p&gt;Counter: {{ count }}&lt;/p&gt;<br>    &lt;button (click)=&quot;increment()&quot;&gt;Add 1&lt;/button&gt;<br>    &lt;ng-content&gt;&lt;/ng-content&gt;<br>  `<br>})<br>export class CounterComponent implements OnChanges, OnInit, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked {<br>  <br>@Input() count: number = 0;<br>  <br>ngOnChanges(changes: SimpleChanges) {<br>    console.log(&#39;ngOnChanges: Input changed&#39;, changes);<br>  }<br>  ngOnInit() {<br>    console.log(&#39;ngOnInit: Component initialized with count&#39;, this.count);<br>  }<br>  ngDoCheck() {<br>    console.log(&#39;ngDoCheck: Change detection running, current count&#39;, this.count);<br>  }<br>  ngAfterContentInit() {<br>    console.log(&#39;ngAfterContentInit: Content projected into component&#39;);<br>  }<br>  ngAfterContentChecked() {<br>    console.log(&#39;ngAfterContentChecked: Content checked&#39;);<br>  }<br>  ngAfterViewInit() {<br>    console.log(&#39;ngAfterViewInit: View initialized&#39;);<br>  }<br>  ngAfterViewChecked() {<br>    console.log(&#39;ngAfterViewChecked: View checked&#39;);<br>  }<br>  increment() {<br>    this.count++;<br>  }<br>}</pre><p>Run the app. You’ll see the previous hooks, then ngAfterViewChecked runs after ngAfterViewInit and during every change detection cycle — like when you click the ‘Add 1’ button. This shows how ngAfterViewChecked lets you verify the view after changes.</p><h4>8. ngOnDestroy: Cleaning Up</h4><p>Finally, let’s add ngOnDestroy. This hook runs just before the component is destroyed, perfect for cleanup. Let’s add a button to the AppComponent to show or hide the CounterComponent. Update app.component.ts:</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { FormsModule } from &#39;@angular/forms&#39;;<br>import { CounterComponent } from &#39;./counter/counter.component&#39;;<br><br>@Component({<br>  selector: &#39;app-root&#39;,<br>  standalone: true,<br>  imports: [FormsModule, CounterComponent],<br>  template: `<br>    &lt;h1&gt;Angular Lifecycle Hooks: ngOnDestroy&lt;/h1&gt;<br>    &lt;p&gt;Initial Count: &lt;input type=&quot;number&quot; [(ngModel)]=&quot;initialCount&quot; (ngModelChange)=&quot;updateCount($event)&quot;&gt;&lt;/p&gt;<br>    &lt;button (click)=&quot;toggleCounter()&quot;&gt;Show/Hide Counter&lt;/button&gt;<br>    &lt;div *ngIf=&quot;showCounter&quot;&gt;<br>      &lt;app-counter [count]=&quot;initialCount&quot;&gt;<br>        &lt;p&gt;Extra Info: This is a counter!&lt;/p&gt;<br>      &lt;/app-counter&gt;<br>    &lt;/div&gt;<br>  `<br>})<br><br>export class AppComponent {<br>  initialCount = 0;<br>  showCounter = true;<br>  updateCount(value: number) {<br>    this.initialCount = value;<br>  }<br>  toggleCounter() {<br>    this.showCounter = !this.showCounter;<br>  }<br>}</pre><p>Update the CounterComponent to include ngOnDestroy (counter.component.ts):</p><pre>import { Component, Input, OnChanges, OnInit, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked, OnDestroy, SimpleChanges } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-counter&#39;,<br>  standalone: true,<br>  template: `<br>    &lt;p&gt;Counter: {{ count }}&lt;/p&gt;<br>    &lt;button (click)=&quot;increment()&quot;&gt;Add 1&lt;/button&gt;<br>    &lt;ng-content&gt;&lt;/ng-content&gt;<br>  `<br>})<br><br>export class CounterComponent implements OnChanges, OnInit, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked, OnDestroy {<br>  <br>@Input() count: number = 0;<br><br>  ngOnChanges(changes: SimpleChanges) {<br>    console.log(&#39;ngOnChanges: Input changed&#39;, changes);<br>  }<br>  ngOnInit() {<br>    console.log(&#39;ngOnInit: Component initialized with count&#39;, this.count);<br>  }<br>  ngDoCheck() {<br>    console.log(&#39;ngDoCheck: Change detection running, current count&#39;, this.count);<br>  }<br>  ngAfterContentInit() {<br>    console.log(&#39;ngAfterContentInit: Content projected into component&#39;);<br>  }<br>  ngAfterContentChecked() {<br>    console.log(&#39;ngAfterContentChecked: Content checked&#39;);<br>  }<br>  ngAfterViewInit() {<br>    console.log(&#39;ngAfterViewInit: View initialized&#39;);<br>  }<br>  ngAfterViewChecked() {<br>    console.log(&#39;ngAfterViewChecked: View checked&#39;);<br>  }<br>  ngOnDestroy() {<br>    console.log(&#39;ngOnDestroy: Component destroyed&#39;);<br>  }<br>  increment() {<br>    this.count++;<br>  }<br>}</pre><p>Run the app. You’ll see all the previous hooks when the component loads. Now, click ‘Show/Hide Counter’ to hide the component — you’ll see ngOnDestroy run because the component is removed. Click the button again to show it, and the lifecycle starts over. This shows how ngOnDestroy lets you clean up before the component is destroyed.</p><h3>Wrapping Up</h3><p>We’ve gone through all eight Angular Component Lifecycle Hooks one by one, using a simple counter component to show when each hook runs. Here’s a quick recap of what we learned:</p><ul><li><strong>ngOnChanges</strong> helps you react to input changes.</li><li><strong>ngOnInit</strong> is for one-time setup.</li><li><strong>ngDoCheck</strong> lets you monitor changes.</li><li><strong>ngAfterContentInit</strong> sets up projected content.</li><li><strong>ngAfterContentChecked</strong> verifies projected content after changes.</li><li><strong>ngAfterViewInit</strong> sets up the view.</li><li><strong>ngAfterViewChecked</strong> verifies the view after changes.</li><li><strong>ngOnDestroy</strong> handles cleanup.</li></ul><p>I hope this step-by-step guide made the lifecycle easy to understand! Try adding these hooks to your own components and experiment with the console logs to see them in action.</p><p>If you want to learn more about Angular, check out my new <a href="https://www.youtube.com/channel/UCgzsUfGTn6n5snVdoIO3uNQ">YouTube channel</a> where I share everything I know about Angular &amp; its latest updates.</p><p>Thank you for reading this article. See you in the next one :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e62a266a6bbb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Master Structural Directives in Angular 19]]></title>
            <link>https://medium.com/@akhilgoyals/master-structural-directives-in-angular-19-903b9851f98d?source=rss-19e4cfb47283------2</link>
            <guid isPermaLink="false">https://medium.com/p/903b9851f98d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Akhil Goyal]]></dc:creator>
            <pubDate>Thu, 27 Mar 2025 20:58:43 GMT</pubDate>
            <atom:updated>2025-03-27T20:58:43.433Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k895L3THgZPW-XbN-Pcd5A.jpeg" /></figure><p>Hello! Today, we’re jumping into structural directives in Angular 19 — or rather, their modern evolution.</p><p>With Angular 19’s latest syntax, we’ve got some shiny new tools like @if, @for, and @switch that replace the old *ngIf, *ngFor, and *ngSwitch. These updates make your templates cleaner and more intuitive, all while keeping the power to dynamically shape your UI.</p><p>Let’s explore them with a fun example — grab your favourite snack, and let’s get going!</p><h3>What Are Structural Directives?</h3><p>Structural directives let you control the structure of your HTML — showing, hiding, or repeating elements based on your data. In the past, we used *ngIf, *ngFor, and *ngSwitch with that asterisk magic.</p><p>But Angular 19 brings a fresh approach with built-in control flow syntax: @if, @for, and @switch. They’re more like regular programming constructs, making your templates feel less like a secret code and more like familiar logic.</p><p>Here’s the lineup:</p><ul><li><strong>@if:</strong> Shows or hides content based on a condition.</li><li><strong>@for: </strong>Loops through data to create elements.</li><li><strong>@switch: </strong>Picks one option from a set, like a switch statement.</li></ul><p>Let’s see how they shine in Angular 19 with a little project!</p><h3>Example: A Book Library</h3><p>Imagine we’re building a book library app. Users can see a list of books, filter by read status, and switch between view modes. We’ll use @if, @for, and @switch with Angular 19’s latest syntax to make it dynamic and sleek. Here we go!</p><h4>Step 1: Set Up the Project</h4><p>If you don’t have an Angular 19 project ready, create one:</p><pre>ng new book-library<br>cd book-library<br>ng serve</pre><p>The new control flow syntax is built into Angular 19, so no extra imports are needed. Let’s dive into the code!</p><h4>Step 2: Build the Component</h4><p>Open app.component.ts and update it like this:</p><pre>import { Component } from &#39;@angular/core&#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 {<br>  books = [<br>    { title: &#39;Dune&#39;, read: true, pages: 412 },<br>    { title: &#39;1984&#39;, read: false, pages: 328 },<br>    { title: &#39;The Hobbit&#39;, read: true, pages: 310 },<br>    { title: &#39;Project Hail Mary&#39;, read: false, pages: 476 }<br>  ];<br>  showReadOnly = false;<br>  viewMode: &#39;list&#39; | &#39;grid&#39; | &#39;details&#39; = &#39;list&#39;;<br>  toggleReadFilter() {<br>    this.showReadOnly = !this.showReadOnly;<br>  }<br>  setView(mode: &#39;list&#39; | &#39;grid&#39; | &#39;details&#39;) {<br>    this.viewMode = mode;<br>  }<br>}</pre><p>Here’s the scoop:</p><ul><li><strong>books: </strong>An array of book objects with title, read status, and page count.</li><li><strong>showReadOnly:</strong> A toggle to filter read books.</li><li><strong>viewMode:</strong> Switches between list, grid, and details views.</li><li><strong>Methods: </strong>toggleReadFilter() flips the filter, and setView() updates the view mode.</li></ul><h4>Step 3: Create the Template with New Syntax</h4><p>Open app.component.html and add this, using Angular 19’s latest control flow:</p><pre>&lt;div class=&quot;container&quot;&gt;<br>  &lt;h2&gt;Book Library&lt;/h2&gt;<br><br>&lt;!-- @if: Show/hide filter message --&gt;<br>  &lt;button (click)=&quot;toggleReadFilter()&quot;&gt;<br>    {{ showReadOnly ? &#39;Show All Books&#39; : &#39;Show Read Only&#39; }}<br>  &lt;/button&gt;<br>  @if (showReadOnly) {<br>    &lt;p&gt;Showing only books you&#39;ve read!&lt;/p&gt;<br>  }<br>  &lt;!-- View Switcher --&gt;<br>  &lt;div class=&quot;view-switcher&quot;&gt;<br>    &lt;button (click)=&quot;setView(&#39;list&#39;)&quot;&gt;List View&lt;/button&gt;<br>    &lt;button (click)=&quot;setView(&#39;grid&#39;)&quot;&gt;Grid View&lt;/button&gt;<br>    &lt;button (click)=&quot;setView(&#39;details&#39;)&quot;&gt;Details View&lt;/button&gt;<br>  &lt;/div&gt;<br>  &lt;!-- @switch: Switch between views --&gt;<br>  @switch (viewMode) {<br>    &lt;!-- List View with @for --&gt;<br>    @case (&#39;list&#39;) {<br>      &lt;ul class=&quot;book-list&quot;&gt;<br>        @for (book of books; track book.title) {<br>          @if (!showReadOnly || book.read) {<br>            &lt;li [class.unread]=&quot;!book.read&quot;&gt;<br>              {{ book.title }} ({{ book.pages }} pages)<br>            &lt;/li&gt;<br>          }<br>        }<br>      &lt;/ul&gt;<br>    }<br>    &lt;!-- Grid View with @for --&gt;<br>    @case (&#39;grid&#39;) {<br>      &lt;div class=&quot;book-grid&quot;&gt;<br>        @for (book of books; track book.title) {<br>          @if (!showReadOnly || book.read) {<br>            &lt;div class=&quot;book-card&quot; [class.unread]=&quot;!book.read&quot;&gt;<br>              {{ book.title }}<br>            &lt;/div&gt;<br>          }<br>        }<br>      &lt;/div&gt;<br>    }<br>    &lt;!-- Details View --&gt;<br>    @case (&#39;details&#39;) {<br>      &lt;div class=&quot;book-details&quot;&gt;<br>        @for (book of books; track book.title) {<br>          @if (!showReadOnly || book.read) {<br>            &lt;p [class.unread]=&quot;!book.read&quot;&gt;<br>              {{ book.title }} - {{ book.read ? &#39;Read&#39; : &#39;Unread&#39; }} <br>              ({{ book.pages }} pages)<br>            &lt;/p&gt;<br>          }<br>        }<br>      &lt;/div&gt;<br>    }<br>    &lt;!-- Default case --&gt;<br>    @default {<br>      &lt;p&gt;Pick a view to see your books!&lt;/p&gt;<br>    }<br>  }<br>&lt;/div&gt;</pre><p>Let’s unpack the new syntax:</p><ul><li><strong>@if:</strong> @if (showReadOnly) shows the filter message only when showReadOnly is true. Inside @for, it filters books based on the read status.</li><li><strong>@for:</strong> @for (book of books; track book.title) loops through the books array, using track (Angular 19’s replacement for trackBy) to optimize performance by tracking each book by its title.</li><li><strong>@switch:</strong> @switch (viewMode) picks a view mode, with @case for each option and @default as a fallback. No more *ngSwitchCase — it’s all streamlined now!</li></ul><h4>Step 4: Add Some Style</h4><p>Add this to app.component.css for a neat look:</p><pre>.container {<br>  max-width: 600px;<br>  margin: 20px auto;<br>  font-family: Arial, sans-serif;<br>}<br>h2 {<br>  text-align: center;<br>}<br>button {<br>  padding: 8px 16px;<br>  background-color: #007bff;<br>  color: white;<br>  border: none;<br>  cursor: pointer;<br>  margin: 5px;<br>}<br>button:hover {<br>  background-color: #0056b3;<br>}<br>.view-switcher {<br>  text-align: center;<br>  margin: 15px 0;<br>}<br>.book-list {<br>  list-style: none;<br>  padding: 0;<br>}<br>.book-list li {<br>  padding: 10px;<br>  border-bottom: 1px solid #ddd;<br>}<br>.book-grid {<br>  display: grid;<br>  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));<br>  gap: 10px;<br>}<br>.book-card {<br>  padding: 15px;<br>  border: 1px solid #ddd;<br>  text-align: center;<br>  border-radius: 5px;<br>}<br>.book-details p {<br>  padding: 10px;<br>  border-bottom: 1px solid #ddd;<br>}<br>.unread {<br>  color: #888;<br>  font-style: italic;<br>}</pre><h4>Step 5: Test It Out!</h4><p>Run ng serve, visit localhost:4200, and have some fun. Toggle the “Show Read Only” button to filter books, and switch between list, grid, and details views. The new @if, @for, and @switch syntax makes the template feel snappy and modern — watch how it adds, removes, or swaps elements effortlessly!</p><h3>Why the New Structural Syntax Rocks</h3><p>Angular 19’s control flow syntax takes structural directives to the next level:</p><ul><li><strong>@if:</strong> Cleaner than *ngIf, with a familiar if vibe and built-in else support (not shown here, but it’s there!).</li><li><strong>@for:</strong> Simpler looping with track for performance, no more separate trackBy functions.</li><li><strong>@switch:</strong> Streamlined and readable, ditching the old *ngSwitchCase clutter.</li></ul><p>It’s all about making your code more intuitive while keeping the power to build dynamic, data-driven UIs.</p><h3>Wrapping Up</h3><p>There you have it — a friendly romp through structural directives in Angular 19 with the latest syntax! We built a book library that filters, loops, and switches views using @if, @for, and @switch. These modern tools make your templates sharper and your app more responsive, all with a fresh, programmer-friendly feel.</p><p>Want to take things further? Try adding a search filter, sorting books by pages, or playing with @else in your @ifs. With Angular 19’s new syntax, you’re ready to direct your UI like a pro!</p><p>If you want to learn more about Angular, check out my new <a href="https://www.youtube.com/channel/UCgzsUfGTn6n5snVdoIO3uNQ">YouTube channel</a> where I share everything I know about Angular &amp; its latest updates.</p><p>Thank you for reading this article. See you in the next one :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=903b9851f98d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Refresher: Data Binding in Angular]]></title>
            <link>https://medium.com/@akhilgoyals/a-refresher-data-binding-in-angular-d1c7fdd63185?source=rss-19e4cfb47283------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1c7fdd63185</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Akhil Goyal]]></dc:creator>
            <pubDate>Thu, 27 Mar 2025 20:34:34 GMT</pubDate>
            <atom:updated>2025-03-27T20:34:34.897Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iToHnEvAtJZf8X-4YAkLrg.jpeg" /></figure><p>Hello! Today, we’re diving into one of Angular’s superpowers: data binding.</p><p>It’s like the glue that connects your TypeScript code to your HTML, making your app feel alive and interactive. Whether you’re displaying data, handling user input, or reacting to clicks, data binding is the magic behind it all.</p><p>Let’s break it down with a fun example and some code — ready to get started?</p><h3>What Is Data Binding?</h3><p>Picture this: you’ve got some data in your component — like a user’s name or a counter — and you want it to show up in your HTML. Or maybe a user types something, and you want that input to update your component instantly. That’s where data binding comes in. It’s Angular’s way of keeping your data and your UI in sync, without you having to manually update everything.</p><p>Angular gives you four flavours of data binding:</p><ol><li><strong>Interpolation: </strong>Displaying data in the template.</li><li><strong>Property Binding:</strong> Setting an element’s properties with data.</li><li><strong>Event Binding:</strong> Listening for user actions (like clicks).</li><li><strong>Two-Way Binding: </strong>Combining input and output in one neat package.</li></ol><p>Let’s see them all in action with a little project!</p><h3>Example: A Task Tracker</h3><p>Let’s build a simple task tracker. Users can add tasks, mark them as done, and see a live count of completed tasks. We’ll use all four types of data binding to make it happen. Here we go!</p><h4>Step 1: Set Up the Project</h4><p>If you don’t have an Angular project ready, create one:</p><pre>ng new task-tracker<br>cd task-tracker<br>ng serve</pre><p>Since two-way binding uses ngModel, we’ll need the FormsModule. Open app.module.ts and update it:</p><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { BrowserModule } from &#39;@angular/platform-browser&#39;;<br>import { FormsModule } from &#39;@angular/forms&#39;; // Import this!<br>import { AppComponent } from &#39;./app.component&#39;;<br><br>@NgModule({<br>  declarations: [AppComponent],<br>  imports: [BrowserModule, FormsModule], // Add FormsModule here<br>  bootstrap: [AppComponent]<br>})<br><br>export class AppModule { }</pre><h4>Step 2: Build the Component</h4><p>Open app.component.ts and replace its contents with this:</p><pre>import { Component } from &#39;@angular/core&#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 {<br>  tasks: { name: string; done: boolean }[] = [<br>    { name: &#39;Learn Angular&#39;, done: false },<br>    { name: &#39;Build a project&#39;, done: false }<br>  ];<br>  newTask: string = &#39;&#39;;<br>  completedCount: number = 0;<br>  addTask() {<br>    if (this.newTask.trim()) {<br>      this.tasks.push({ name: this.newTask, done: false });<br>      this.newTask = &#39;&#39;; // Clear the input<br>    }<br>  }<br>  toggleTask(task: { name: string; done: boolean }) {<br>    task.done = !task.done;<br>    this.updateCompletedCount();<br>  }<br>  updateCompletedCount() {<br>    this.completedCount = this.tasks.filter(task =&gt; task.done).length;<br>  }<br>}</pre><p>Here’s the rundown:</p><ul><li><strong>tasks:</strong> An array of task objects with a name and done status.</li><li><strong>newTask:</strong> Holds the user’s input for a new task.</li><li><strong>completedCount: </strong>Tracks how many tasks are done.</li><li><strong>Methods: </strong>addTask() adds a new task, toggleTask() flips the done status, and updateCompletedCount() keeps the count fresh.</li></ul><h4>Step 3: Create the Template</h4><p>Open app.component.html and add this:</p><pre>&lt;div class=&quot;container&quot;&gt;<br>  &lt;h2&gt;Task Tracker&lt;/h2&gt;<br><br>&lt;!-- Interpolation: Displaying the completed count --&gt;<br>  &lt;p&gt;Completed Tasks: {{ completedCount }} / {{ tasks.length }}&lt;/p&gt;<br>  &lt;!-- Two-Way Binding: Input for new tasks --&gt;<br>  &lt;div class=&quot;form-group&quot;&gt;<br>    &lt;input<br>      type=&quot;text&quot;<br>      [(ngModel)]=&quot;newTask&quot;<br>      placeholder=&quot;Add a new task&quot;<br>      class=&quot;form-control&quot;<br>    /&gt;<br>    &lt;!-- Property Binding: Disable button if input is empty --&gt;<br>    &lt;button [disabled]=&quot;!newTask.trim()&quot; (click)=&quot;addTask()&quot;&gt;Add Task&lt;/button&gt;<br>  &lt;/div&gt;<br>  &lt;!-- Event Binding: Toggle task status --&gt;<br>  &lt;ul class=&quot;task-list&quot;&gt;<br>    &lt;li *ngFor=&quot;let task of tasks&quot;&gt;<br>      &lt;input<br>        type=&quot;checkbox&quot;<br>        [checked]=&quot;task.done&quot;<br>        (change)=&quot;toggleTask(task)&quot;<br>      /&gt;<br>      &lt;span [ngClass]=&quot;{ &#39;done&#39;: task.done }&quot;&gt;{{ task.name }}&lt;/span&gt;<br>    &lt;/li&gt;<br>  &lt;/ul&gt;<br>&lt;/div&gt;</pre><p>Let’s break it down:</p><ul><li><strong>Interpolation:</strong> {{ completedCount }} shows the number of completed tasks.</li><li><strong>Property Binding:</strong> [disabled]=”!newTask.trim()” disables the button if the input is empty; [checked]=”task.done” sets the checkbox state.</li><li><strong>Event Binding:</strong> (click)=”addTask()” triggers adding a task; (change)=”toggleTask(task)” updates the task status.</li><li><strong>Two-Way Binding: </strong>[(ngModel)]=”newTask” ties the input value to newTask, updating both ways instantly.</li></ul><h4>Step 4: Add Some Style</h4><p>Pop this into app.component.css for a clean look:</p><pre>.container {<br>  max-width: 500px;<br>  margin: 20px auto;<br>  font-family: Arial, sans-serif;<br>}<br>h2, p {<br>  text-align: center;<br>}<br>.form-group {<br>  display: flex;<br>  gap: 10px;<br>  margin-bottom: 20px;<br>}<br>.form-control {<br>  flex: 1;<br>  padding: 8px;<br>  box-sizing: border-box;<br>}<br>button {<br>  padding: 8px 16px;<br>  background-color: #007bff;<br>  color: white;<br>  border: none;<br>  cursor: pointer;<br>}<br>button:disabled {<br>  background-color: #cccccc;<br>  cursor: not-allowed;<br>}<br>.task-list {<br>  list-style: none;<br>  padding: 0;<br>}<br>.task-list li {<br>  display: flex;<br>  align-items: center;<br>  gap: 10px;<br>  margin-bottom: 10px;<br>}<br>.done {<br>  text-decoration: line-through;<br>  color: #888;<br>}</pre><h4>Step 5: Test It Out!</h4><p>Run ng serve, head to localhost:4200, and give it a spin. Add a few tasks, check some off, and watch the completed count update in real-time. Type in the input, and see how the “Add Task” button lights up only when there’s text. It’s all thanks to data binding keeping everything in sync!</p><h3>Why Data Binding Rocks</h3><p>Data binding is the heart of Angular’s reactivity. Here’s why it’s awesome:</p><ul><li><strong>Interpolation: </strong>Shows data effortlessly — no manual DOM updates needed.</li><li><strong>Property Binding:</strong> Gives you control over element properties dynamically.</li><li><strong>Event Binding:</strong> Makes your app respond to users like a charm.</li><li><strong>Two-Way Binding: </strong>Keeps inputs and data in perfect harmony with minimal effort.</li></ul><p>Together, they make your app feel seamless and alive, whether you’re building a task tracker or something way bigger.</p><h3>Wrapping Up</h3><p>And there you have it — a friendly tour of data binding in Angular! We built a task tracker that uses all four types of binding to display data, handle input, and react to clicks. With interpolation, property binding, event binding, and two-way binding, you’ve got the tools to connect your app’s pieces like a pro.</p><p>Want to keep going? Try adding a delete button for tasks, styling completed tasks differently, or even saving tasks to local storage. Angular’s data binding makes it all a breeze.</p><p>If you want to learn more about Angular, check out my new <a href="https://www.youtube.com/channel/UCgzsUfGTn6n5snVdoIO3uNQ">YouTube channel</a> where I share everything I know about Angular &amp; its latest updates.</p><p>Thank you for reading this article. See you in the next one :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1c7fdd63185" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refresher: Angular’s @Input and @Output Decorators]]></title>
            <link>https://medium.com/@akhilgoyals/refresher-angulars-input-and-output-decorators-6351c3a3416f?source=rss-19e4cfb47283------2</link>
            <guid isPermaLink="false">https://medium.com/p/6351c3a3416f</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Akhil Goyal]]></dc:creator>
            <pubDate>Wed, 26 Mar 2025 22:41:42 GMT</pubDate>
            <atom:updated>2025-03-27T16:22:22.053Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rveFEAie3xN-te2sBeitXg.jpeg" /></figure><p>Hello! Today, we’re diving into two of Angular’s coolest tools: @Input and @Output. These directives are all about passing data between components, whether it’s sending info down to a child or bubbling events back up to a parent. It’s like setting up a little family chat group — simple and powerful.</p><p>Let’s break it down with a fun example and some code to play with!</p><h3>What Are @Input and @Output?</h3><p>Imagine your Angular app as a tree of components. Sometimes, a parent component needs to share data with its kids (that’s @Input), and other times, the kids need to tell the parent something happened (that’s @Output). Together, they create a two-way communication highway that keeps your app humming along.</p><ul><li>@Input: Lets a parent component send data to a child component. Think of it as passing a note down the table.</li><li>@Output: Lets a child component send events (and data) back to the parent. It’s like the child shouting, “Hey, something cool just happened!”</li></ul><p>Ready to see how they work? Let’s build something together!</p><h3>Example: A Voting App</h3><p>Let’s create a mini voting app. We’ll have a ParentComponent that lists candidates and a ChildComponent that displays each candidate with a “Vote” button. The parent will send candidate data to the child using @Input, and the child will tell the parent when someone votes using @Output. Here we go!</p><h4>Step 1: Set Up the Project</h4><p>If you don’t have an Angular project yet, set one up:</p><pre>ng new voting-app<br>cd voting-app<br>ng serve</pre><p>Now, generate a child component:</p><pre>ng generate component candidate</pre><h4>Step 2: Build the Child Component</h4><p>Open candidate.component.ts and add this:</p><pre>import { Component, Input, Output, EventEmitter } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-candidate&#39;,<br>  templateUrl: &#39;./candidate.component.html&#39;,<br>  styleUrls: [&#39;./candidate.component.css&#39;]<br>})<br><br>export class CandidateComponent {<br>  @Input() name: string = &#39;&#39;; // Data coming from the parent<br>  @Input() votes: number = 0; // More data from the parent<br>  @Output() voteEvent = new EventEmitter&lt;string&gt;(); // Event to send back to the parent<br>  onVote() {<br>    this.voteEvent.emit(this.name); // Tell the parent this candidate got a vote<br>  }<br>}</pre><p>Here’s what’s happening:</p><ul><li>@Input() name and @Input() votes: Properties the parent will set.</li><li>@Output() voteEvent: An EventEmitter to notify the parent when the “Vote” button is clicked.</li><li>onVote(): Emits the candidate’s name when clicked.</li></ul><p>Now, the template in candidate.component.html:</p><pre>&lt;div class=&quot;candidate-card&quot;&gt;<br>  &lt;h3&gt;{{ name }}&lt;/h3&gt;<br>  &lt;p&gt;Votes: {{ votes }}&lt;/p&gt;<br>  &lt;button (click)=&quot;onVote()&quot;&gt;Vote for {{ name }}&lt;/button&gt;<br>&lt;/div&gt;</pre><p>And some quick styles in candidate.component.css:</p><pre>.candidate-card {<br>  border: 1px solid #ddd;<br>  padding: 15px;<br>  margin: 10px;<br>  border-radius: 5px;<br>  text-align: center;<br>}<br>button {<br>  padding: 8px 16px;<br>  background-color: #28a745;<br>  color: white;<br>  border: none;<br>  cursor: pointer;<br>}<br>button:hover {<br>  background-color: #218838;<br>}</pre><h4>Step 3: Set Up the Parent Component</h4><p>Open app.component.ts and update it like this:</p><pre>import { Component } from &#39;@angular/core&#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 {<br>  candidates = [<br>    { name: &#39;Alice&#39;, votes: 5 },<br>    { name: &#39;Bob&#39;, votes: 3 },<br>    { name: &#39;Charlie&#39;, votes: 7 }<br>  ];<br>  onVote(candidateName: string) {<br>    const candidate = this.candidates.find(c =&gt; c.name === candidateName);<br>    if (candidate) {<br>      candidate.votes += 1;<br>    }<br>    console.log(`${candidateName} got a vote! New totals:`, this.candidates);<br>  }<br>}</pre><p>Here’s the logic:</p><ul><li>candidates: An array of objects with names and vote counts.</li><li>onVote(): Updates the vote count when the child sends an event.</li></ul><p>Now, the template in app.component.html:</p><pre>&lt;div class=&quot;container&quot;&gt;<br>  &lt;h2&gt;Vote for Your Favorite Candidate!&lt;/h2&gt;<br>  &lt;app-candidate<br>    *ngFor=&quot;let candidate of candidates&quot;<br>    [name]=&quot;candidate.name&quot;<br>    [votes]=&quot;candidate.votes&quot;<br>    (voteEvent)=&quot;onVote($event)&quot;<br>  &gt;&lt;/app-candidate&gt;<br>&lt;/div&gt;</pre><p>And some basic styles in app.component.css:</p><pre>.container {<br>  max-width: 600px;<br>  margin: 20px auto;<br>  font-family: Arial, sans-serif;<br>}<br>h2 {<br>  text-align: center;<br>}</pre><p>Let’s unpack the template:</p><ul><li>*ngFor: Loops through the candidates array.</li><li>[name]=”candidate.name”: Passes the name to the child via @Input.</li><li>[votes]=”candidate.votes”: Passes the vote count to the child.</li><li>(voteEvent)=”onVote($event)”: Listens for the @Output event and calls onVote with the emitted data.</li></ul><h4>Step 4: Test It Out!</h4><p>Run ng serve, head to localhost:4200, and check it out. You’ll see three candidates — Alice, Bob, and Charlie — with their vote counts. Click a “Vote” button, and watch the count go up in real-time. Open the console to see the updated totals logged. How cool is that?</p><h4>How @Input and @Output Work Together</h4><ul><li>@Input: The parent sends name and votes to the child component. It’s one-way traffic — parent to child.</li><li>@Output: The child sends the voteEvent back to the parent with the candidate’s name. This closes the loop, letting the parent react.</li></ul><p>It’s like a relay race: the parent passes the baton (data) to the child, and the child passes it back (events) when something happens. Together, they keep your app in sync!</p><h3>Why Use @Input and @Output?</h3><p>These directives are perfect when:</p><ul><li>You’re building reusable components that need to talk to their parents or siblings.</li><li>You want a clean, predictable way to share data and handle events.</li><li>Your app has a clear parent-child hierarchy (most Angular apps do!).</li></ul><p>Sure, for bigger apps, you might lean on services or state management (like NgRx), but @Input and @Output are the bread and butter of component communication.</p><h3>Wrapping Up</h3><p>And there you have it — a friendly spin through @Input and @Output in Angular! We built a little voting app, passed data from parent to child, and sent events back up the chain. With these tools, your components can chat like old pals, making your app more dynamic and fun to build.</p><p>Want to take it further? Try adding a reset button in the parent, passing more complex data with @Input, or styling it up. The possibilities are endless, and Angular’s got the tools to make it happen.</p><p>If you want to learn more about Angular, check out my new <a href="https://www.youtube.com/channel/UCgzsUfGTn6n5snVdoIO3uNQ">YouTube channel</a> where I share everything I know about Angular &amp; its latest updates.</p><p>Thank you for reading this article. See you in the next one :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6351c3a3416f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Reactive Forms in Angular]]></title>
            <link>https://medium.com/@akhilgoyals/getting-started-with-reactive-forms-in-angular-bd6737054acd?source=rss-19e4cfb47283------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd6737054acd</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Akhil Goyal]]></dc:creator>
            <pubDate>Wed, 26 Mar 2025 00:24:54 GMT</pubDate>
            <atom:updated>2025-03-26T00:24:54.574Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AaeRnuw1zLF1vFMJpvApWA.jpeg" /></figure><p>Hello! Last time, we explored Template Forms, but today, we’re diving into Reactive Forms in Angular. These are all about control, flexibility, and TypeScript awesomeness. Whether you’re handling complex forms or just want more power over your data, Reactive Forms are here to save the day. Let’s break it down together with a fun example — grab your coffee, and let’s get started!</p><h3>What Are Reactive Forms?</h3><p>Reactive Forms are like the superhero version of forms in Angular. Instead of relying on HTML directives like Template Forms, you define everything in your TypeScript code — structure, validation, and behavior. It’s a bit more setup upfront, but the payoff is huge: you get fine-tuned control, easier testing, and the ability to handle dynamic forms.</p><p>Think of it as building a form with a blueprint. You tell Angular exactly what fields you want, how they should behave, and what rules they follow — all from your component. It’s perfect for complex scenarios like multi-step forms or when you need to react to user input in real-time. Let’s see it in action!</p><h3>Setting Up Reactive Forms in Angular</h3><p>First things first, let’s assume you’ve got an Angular project ready. If not, set one up with:</p><pre>ng new reactive-forms-demo<br>cd reactive-forms-demo<br>ng serve</pre><p>Next, we need the ReactiveFormsModule. Open app.module.ts and update it like this:</p><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { BrowserModule } from &#39;@angular/platform-browser&#39;;<br>import { ReactiveFormsModule } from &#39;@angular/forms&#39;; // Import this!<br>import { AppComponent } from &#39;./app.component&#39;;<br><br>@NgModule({<br>  declarations: [AppComponent],<br>  imports: [BrowserModule, ReactiveFormsModule], // Add ReactiveFormsModule here<br>  bootstrap: [AppComponent]<br>})<br>export class AppModule { }</pre><p>With that, we’re ready to roll. Let’s build something exciting!</p><h3>Example: A Job Application Form</h3><p>Imagine we’re creating a form for job applicants. They’ll enter their full name, email, years of experience, and a skills checklist. Reactive Forms will give us the power to manage this with ease. Here we go!</p><h4>Step 1: Build the Component Logic</h4><p>Open app.component.ts and replace its contents with this:</p><pre>import { Component, OnInit } from &#39;@angular/core&#39;;<br>import { FormBuilder, FormGroup, Validators } 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>  jobForm: FormGroup;<br>  submitted = false;<br>  constructor(private fb: FormBuilder) {<br>    this.jobForm = this.fb.group({<br>      fullName: [&#39;&#39;, [Validators.required, Validators.minLength(3)]],<br>      email: [&#39;&#39;, [Validators.required, Validators.email]],<br>      experience: [0, [Validators.required, Validators.min(0), Validators.max(50)]],<br>      skills: this.fb.group({<br>        angular: [false],<br>        typescript: [false],<br>        javascript: [false]<br>      })<br>    });<br>  }<br>  ngOnInit() {}<br>  onSubmit() {<br>    if (this.jobForm.valid) {<br>      this.submitted = true;<br>      console.log(&#39;Form submitted!&#39;, this.jobForm.value);<br>    }<br>  }<br>  // Getter for easier template access<br>  get f() {<br>    return this.jobForm.controls;<br>  }<br>}</pre><p>Let’s break this down:</p><ul><li>FormBuilder: A handy service that simplifies creating form groups and controls.</li><li>FormGroup: Represents the entire form, with nested controls for each field.</li><li>Validators: Built-in rules like required, minLength, and email to enforce data quality.</li><li>skills: A nested FormGroup for the checkbox list — Reactive Forms make this a breeze!</li><li>get f(): A shortcut to access form controls in the template.</li></ul><h4>Step 2: Create the Template</h4><p>Now, open app.component.html and add this:</p><pre>&lt;div class=&quot;container&quot;&gt;<br>  &lt;h2&gt;Apply for Your Dream Job!&lt;/h2&gt;<br>  &lt;form [formGroup]=&quot;jobForm&quot; (ngSubmit)=&quot;onSubmit()&quot;&gt;<br>    &lt;!-- Full Name --&gt;<br>    &lt;div class=&quot;form-group&quot;&gt;<br>      &lt;label for=&quot;fullName&quot;&gt;Full Name:&lt;/label&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        id=&quot;fullName&quot;<br>        formControlName=&quot;fullName&quot;<br>        class=&quot;form-control&quot;<br>      /&gt;<br>      &lt;div *ngIf=&quot;f.fullName.touched &amp;&amp; f.fullName.invalid&quot; class=&quot;error&quot;&gt;<br>        &lt;div *ngIf=&quot;f.fullName.errors?.[&#39;required&#39;]&quot;&gt;Name is required.&lt;/div&gt;<br>        &lt;div *ngIf=&quot;f.fullName.errors?.[&#39;minlength&#39;]&quot;&gt;<br>          Name must be at least 3 characters.<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;!-- Email --&gt;<br>    &lt;div class=&quot;form-group&quot;&gt;<br>      &lt;label for=&quot;email&quot;&gt;Email:&lt;/label&gt;<br>      &lt;input<br>        type=&quot;email&quot;<br>        id=&quot;email&quot;<br>        formControlName=&quot;email&quot;<br>        class=&quot;form-control&quot;<br>      /&gt;<br>      &lt;div *ngIf=&quot;f.email.touched &amp;&amp; f.email.invalid&quot; class=&quot;error&quot;&gt;<br>        &lt;div *ngIf=&quot;f.email.errors?.[&#39;required&#39;]&quot;&gt;Email is required.&lt;/div&gt;<br>        &lt;div *ngIf=&quot;f.email.errors?.[&#39;email&#39;]&quot;&gt;Enter a valid email.&lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>    &lt;!-- Experience --&gt;<br>    &lt;div class=&quot;form-group&quot;&gt;<br>      &lt;label for=&quot;experience&quot;&gt;Years of Experience:&lt;/label&gt;<br>      &lt;input<br>        type=&quot;number&quot;<br>        id=&quot;experience&quot;<br>        formControlName=&quot;experience&quot;<br>        class=&quot;form-control&quot;<br>      /&gt;<br>      &lt;div *ngIf=&quot;f.experience.touched &amp;&amp; f.experience.invalid&quot; class=&quot;error&quot;&gt;<br>        &lt;div *ngIf=&quot;f.experience.errors?.[&#39;required&#39;]&quot;&gt;<br>          Experience is required.<br>        &lt;/div&gt;<br>        &lt;div *ngIf=&quot;f.experience.errors?.[&#39;min&#39;] || f.experience.errors?.[&#39;max&#39;]&quot;&gt;<br>          Enter a value between 0 and 50.<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>    &lt;!-- Skills --&gt;<br>    &lt;div class=&quot;form-group&quot;&gt;<br>      &lt;label&gt;Skills:&lt;/label&gt;<br>      &lt;div formGroupName=&quot;skills&quot;&gt;<br>        &lt;label&gt;<br>          &lt;input type=&quot;checkbox&quot; formControlName=&quot;angular&quot; /&gt; Angular<br>        &lt;/label&gt;<br>        &lt;label&gt;<br>          &lt;input type=&quot;checkbox&quot; formControlName=&quot;typescript&quot; /&gt; TypeScript<br>        &lt;/label&gt;<br>        &lt;label&gt;<br>          &lt;input type=&quot;checkbox&quot; formControlName=&quot;javascript&quot; /&gt; JavaScript<br>        &lt;/label&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>    &lt;!-- Submit Button --&gt;<br>    &lt;button type=&quot;submit&quot; [disabled]=&quot;jobForm.invalid&quot;&gt;Submit Application&lt;/button&gt;<br>  &lt;/form&gt;<br>  &lt;!-- Display Submitted Data --&gt;<br>  &lt;div *ngIf=&quot;submitted&quot;&gt;<br>    &lt;h3&gt;Application Received!&lt;/h3&gt;<br>    &lt;p&gt;Name: {{ jobForm.value.fullName }}&lt;/p&gt;<br>    &lt;p&gt;Email: {{ jobForm.value.email }}&lt;/p&gt;<br>    &lt;p&gt;Experience: {{ jobForm.value.experience }} years&lt;/p&gt;<br>    &lt;p&gt;Skills: <br>      {{ jobForm.value.skills.angular ? &#39;Angular &#39; : &#39;&#39; }}<br>      {{ jobForm.value.skills.typescript ? &#39;TypeScript &#39; : &#39;&#39; }}<br>      {{ jobForm.value.skills.javascript ? &#39;JavaScript&#39; : &#39;&#39; }}<br>    &lt;/p&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;<br></pre><p>Here’s what’s happening:</p><ul><li>[formGroup]=”jobForm”: Binds the form to our FormGroup.</li><li>formControlName: Links each input to a control in the FormGroup.</li><li>Validation messages: Show up when a field is touched and invalid, using the f getter for simplicity.</li><li>Nested formGroupName=”skills”: Manages the skills checkboxes as a group.</li></ul><h4>Step 3: Add Some Style</h4><p>Reuse the CSS from the Template Forms example (or tweak it if you’re feeling creative). Drop this into app.component.css:</p><pre>.container {<br>  max-width: 500px;<br>  margin: 20px auto;<br>  font-family: Arial, sans-serif;<br>}<br><br>.form-group {<br>  margin-bottom: 15px;<br>}<br>.form-control {<br>  width: 100%;<br>  padding: 8px;<br>  box-sizing: border-box;<br>}<br>.error {<br>  color: red;<br>  font-size: 12px;<br>}<br>button {<br>  padding: 10px 20px;<br>  background-color: #007bff;<br>  color: white;<br>  border: none;<br>  cursor: pointer;<br>}<br>button:disabled {<br>  background-color: #cccccc;<br>  cursor: not-allowed;<br>}</pre><h4>Step 4: Test It Out!</h4><p>Run ng serve, head to localhost:4200, and give it a try. Play with the fields — skip the name, enter a bad email, or crank the experience to 100. The validation kicks in, and once everything’s good, hit “Submit Application” to see your data displayed. Sweet, huh?</p><p>Why Use Reactive Forms?</p><p>Reactive Forms are your go-to when:</p><ul><li>You need precise control over form logic and validation.</li><li>Your form is dynamic (e.g., adding fields on the fly).</li><li>You want to unit test your form behavior (TypeScript makes this easier!).</li></ul><p>Sure, they take a bit more setup than Template Forms, but the flexibility is worth it. Complex forms? Custom validators? Real-time updates? Reactive Forms have your back.</p><h3>Wrapping Up</h3><p>There you go — a fun and friendly intro to Reactive Forms in Angular! We built a job application form, wired it up with TypeScript, and added some slick validation. With FormBuilder, FormGroup, and a dash of Angular magic, you’re ready to tackle any form challenge.</p><p>Want to keep going? Try adding custom validators, making fields conditional, or even syncing with a backend.</p><p>If you want to learn more about Angular, check out my new <a href="https://www.youtube.com/channel/UCgzsUfGTn6n5snVdoIO3uNQ">YouTube channel</a> where I share everything I know about Angular &amp; its latest updates.</p><p>Thank you for reading this article. See you in the next one :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd6737054acd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Template Forms in Angular]]></title>
            <link>https://medium.com/@akhilgoyals/mastering-template-forms-in-angular-f8c54c853592?source=rss-19e4cfb47283------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8c54c853592</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Akhil Goyal]]></dc:creator>
            <pubDate>Tue, 25 Mar 2025 13:22:22 GMT</pubDate>
            <atom:updated>2025-03-25T13:22:22.746Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XKY_4fO0G1GbTFcrg3g2Fg.jpeg" /></figure><p>Hey there, Angular enthusiasts! If you’re diving into Angular and wondering how to handle forms in a simple yet powerful way, you’re in the right place.</p><p>Today, we’re going to explore Template Forms — one of Angular’s two approaches to building forms (the other being Reactive Forms, but that’s a story for another day).</p><p>Template Forms are perfect when you want something quick, intuitive, and driven by your HTML templates.</p><p>Let’s break it down together, step by step, with a fun example to bring it all to life!</p><h3>What Are Template Forms?</h3><p>Imagine you’re building a signup page — users need to enter their name, email, and maybe a password. With Template Forms, you let the HTML template do most of the heavy lifting. You add some Angular directives (like ngModel) to your form elements, tie them to your component, and voilà — Angular handles the data binding and validation for you. It’s like giving your HTML superpowers without drowning in TypeScript code.</p><p>Template Forms are ideal for simpler forms where you don’t need complex logic or dynamic behavior. They’re easy to set up, and if you’re comfortable with HTML, you’ll feel right at home. Ready to see how it works? Let’s jump in!</p><h3>Setting Up Template Forms in Angular</h3><p>Before we get coding, make sure you’ve got an Angular project ready. If not, fire up your terminal and run:</p><pre>ng new template-forms-demo<br>cd template-forms-demo<br>ng serve</pre><p>Once your app is humming along, we need to tell Angular we’re using Template Forms. Open app.module.ts and import the FormsModule like this:</p><pre>import { NgModule } from &#39;@angular/core&#39;;<br>import { BrowserModule } from &#39;@angular/platform-browser&#39;;<br>import { FormsModule } from &#39;@angular/forms&#39;; // Import this!<br>import { AppComponent } from &#39;./app.component&#39;;<br><br>@NgModule({<br>  declarations: [AppComponent],<br>  imports: [BrowserModule, FormsModule], // Add FormsModule here<br>  bootstrap: [AppComponent]<br>})<br><br>export class AppModule { }</pre><p>That’s it! FormsModule gives us access to all the goodies we need for Template Forms. Now, let’s build something fun.</p><h3>Example: A Simple Event Registration Form</h3><p>Let’s say we’re creating a form for people to sign up for a coding workshop. They’ll enter their name, email, and whether they’re bringing a friend. Here’s how we’ll do it.</p><h4>Step 1: Build the Template</h4><p>Open app.component.html and replace its contents with this:</p><pre>&lt;div class=&quot;container&quot;&gt;<br>  &lt;h2&gt;Sign Up for Our Coding Workshop!&lt;/h2&gt;<br>  &lt;form #workshopForm=&quot;ngForm&quot; (ngSubmit)=&quot;onSubmit()&quot;&gt;<br>    &lt;!-- Name Field --&gt;<br>    &lt;div class=&quot;form-group&quot;&gt;<br>      &lt;label for=&quot;name&quot;&gt;Your Name:&lt;/label&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        id=&quot;name&quot;<br>        name=&quot;name&quot;<br>        ngModel<br>        required<br>        minlength=&quot;2&quot;<br>        #name=&quot;ngModel&quot;<br>        class=&quot;form-control&quot;<br>      /&gt;<br>      &lt;div *ngIf=&quot;name.invalid &amp;&amp; name.touched&quot; class=&quot;error&quot;&gt;<br>        Please enter a name (at least 2 characters).<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;!-- Email Field --&gt;<br>    &lt;div class=&quot;form-group&quot;&gt;<br>      &lt;label for=&quot;email&quot;&gt;Your Email:&lt;/label&gt;<br>      &lt;input<br>        type=&quot;email&quot;<br>        id=&quot;email&quot;<br>        name=&quot;email&quot;<br>        ngModel<br>        required<br>        email<br>        #email=&quot;ngModel&quot;<br>        class=&quot;form-control&quot;<br>      /&gt;<br>      &lt;div *ngIf=&quot;email.invalid &amp;&amp; email.touched&quot; class=&quot;error&quot;&gt;<br>        A valid email is required.<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>    &lt;!-- Bringing a Friend Checkbox --&gt;<br>    &lt;div class=&quot;form-group&quot;&gt;<br>      &lt;label&gt;<br>        &lt;input<br>          type=&quot;checkbox&quot;<br>          name=&quot;bringFriend&quot;<br>          ngModel<br>          #bringFriend=&quot;ngModel&quot;<br>        /&gt;<br>        Bringing a friend?<br>      &lt;/label&gt;<br>    &lt;/div&gt;<br>    &lt;!-- Submit Button --&gt;<br>    &lt;button type=&quot;submit&quot; [disabled]=&quot;workshopForm.invalid&quot;&gt;Register&lt;/button&gt;<br>  &lt;/form&gt;<br>  &lt;!-- Display Submitted Data --&gt;<br>  &lt;div *ngIf=&quot;submitted&quot;&gt;<br>    &lt;h3&gt;Thanks for signing up!&lt;/h3&gt;<br>    &lt;p&gt;Name: {{ user.name }}&lt;/p&gt;<br>    &lt;p&gt;Email: {{ user.email }}&lt;/p&gt;<br>    &lt;p&gt;Bringing a friend? {{ user.bringFriend ? &#39;Yes&#39; : &#39;No&#39; }}&lt;/p&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p>Let’s unpack what’s happening here:</p><ul><li>#workshopForm=”ngForm”: This creates a reference to the form and tracks its state (valid, invalid, etc.).</li><li>ngModel: This binds the input values to properties in our component (more on that soon).</li><li>#name=”ngModel”: A local reference to check the field’s state (e.g., name.invalid or name.touched).</li><li>required, minlength, email: Built-in HTML5 validators that Angular picks up automatically.</li><li>(ngSubmit)=”onSubmit()”: Triggers when the form is submitted.</li></ul><h4>Step 2: Style It Up (Optional)</h4><p>For a polished look, add this to app.component.css:</p><pre>.container {<br>  max-width: 500px;<br>  margin: 20px auto;<br>  font-family: Arial, sans-serif;<br>}<br><br>.form-group {<br>  margin-bottom: 15px;<br>}<br>.form-control {<br>  width: 100%;<br>  padding: 8px;<br>  box-sizing: border-box;<br>}<br>.error {<br>  color: red;<br>  font-size: 12px;<br>}<br>button {<br>  padding: 10px 20px;<br>  background-color: #007bff;<br>  color: white;<br>  border: none;<br>  cursor: pointer;<br>}<br>button:disabled {<br>  background-color: #cccccc;<br>  cursor: not-allowed;<br>}</pre><h4>Step 3: Wire It Up in the Component</h4><p>Now, let’s head to app.component.ts and add the logic:</p><pre>import { Component } from &#39;@angular/core&#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 {<br>  user = {<br>    name: &#39;&#39;,<br>    email: &#39;&#39;,<br>    bringFriend: false<br>  };<br>  submitted = false;<br>  onSubmit() {<br>    this.submitted = true;<br>    console.log(&#39;Form submitted!&#39;, this.user);<br>  }<br>}</pre><p>Here’s what’s going on:</p><ul><li>user: An object to hold the form data, automatically populated by ngModel.</li><li>submitted: A flag to show the confirmation message after submission.</li><li>onSubmit(): Runs when the form is submitted, logging the data and updating the UI.</li></ul><p>Step 4: Test It Out!</p><p>Run ng serve, open your browser to localhost:4200, and play with the form. Try leaving fields blank or entering an invalid email — you’ll see the validation messages pop up. Once everything’s filled out correctly, hit “Register” and watch your data appear below the form. Pretty cool, right?</p><h3>Why Use Template Forms?</h3><p>Template Forms shine when:</p><ul><li>Your form is straightforward (no crazy logic or dynamic fields).</li><li>You want to keep most of the work in the template.</li><li>You’re building something quick and don’t need the extra control of Reactive Forms.</li></ul><p>That said, if your form grows complex — say, with conditional fields or custom validation — Reactive Forms might be a better fit. But for now, Template Forms have got you covered!</p><h3>Wrapping Up</h3><p>And there you have it — a friendly dive into Template Forms in Angular 19! We built a little event registration form, added some validation, and made it look nice. With ngModel, ngForm, and a sprinkle of Angular magic, you can whip up forms in no time.</p><p>Want to take it further? Try adding more fields, experimenting with custom validators, or styling it. The possibilities are endless, and Angular’s got your back.</p><p>If you want to learn more about Angular, check out my new <a href="https://www.youtube.com/channel/UCgzsUfGTn6n5snVdoIO3uNQ">YouTube channel</a> where I share everything I know about Angular &amp; its latest updates.</p><p>Thank you for reading this article. I hope to see you in the next one :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8c54c853592" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering JavaScript Scope with IIFEs]]></title>
            <link>https://medium.com/@akhilgoyals/mastering-javascript-scope-with-iifes-60de101b907d?source=rss-19e4cfb47283------2</link>
            <guid isPermaLink="false">https://medium.com/p/60de101b907d</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Akhil Goyal]]></dc:creator>
            <pubDate>Thu, 20 Feb 2025 16:15:37 GMT</pubDate>
            <atom:updated>2025-02-20T16:15:37.768Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vT6l3hz2cvm2kaPsR3AZgA.jpeg" /></figure><p>One of the biggest pitfalls in JavaScript development is <strong>global scope pollution</strong>. When too many variables and functions exist in the global namespace, they can easily conflict with each other, leading to <strong>hard-to-debug errors</strong>.</p><p>Before ES6 introduced import/export for modularity, developers had to get creative to keep their code self-contained. Their solution? <strong>Immediately Invoked Function Expressions (IIFEs).</strong></p><p>Even though modern JavaScript now has built-in modules, <strong>IIFEs are still useful in many situations</strong> — especially when working with older codebases, optimizing performance, or isolating small scripts.</p><p>Let’s break down what IIFEs are, why they were crucial, and why you should still understand them today.</p><h3>What is an IIFE?</h3><p>An <strong>Immediately Invoked Function Expression (IIFE)</strong> is a function that:</p><p>✓ <strong>Is defined as an expression</strong><br>✓ <strong>Executes immediately</strong> after being created<br>✓ <strong>Creates a private scope</strong>, keeping variables and functions contained</p><p>Here’s a simple example:</p><pre>(function() {<br>    console.log(&quot;Hello from an IIFE!&quot;);<br>})();</pre><h3>Breaking it Down</h3><ol><li>The function is wrapped in parentheses (function() { ... }), making it an <strong>expression</strong> instead of a declaration.</li><li>The () at the end <strong>immediately executes</strong> the function.</li><li>Any variables inside the function remain <strong>isolated</strong>, avoiding conflicts with the global scope.</li></ol><p>In short, IIFEs allow us to <strong>run code instantly while keeping it self-contained</strong>.</p><h3>Why Were IIFEs Used Before ES6?</h3><p>Before JavaScript had modules, developers relied on IIFEs for three key reasons:</p><h3>Preventing Global Variable Conflicts</h3><p>Imagine you have two separate scripts, each defining a function called calculate(). If both are in the global scope, one could <strong>overwrite</strong> the other, causing unpredictable behavior.</p><p>By wrapping each function inside an IIFE, their variables and functions stay <strong>private</strong>, preventing accidental overwrites.</p><pre>(function() {<br>    function calculate() {<br>        console.log(&quot;Calculating...&quot;);<br>    }<br>    calculate();<br>})();</pre><p>Now, calculate() is safely contained within its own scope.</p><h3>Encapsulating Code for Modular Design</h3><p>IIFEs allowed developers to structure their code in a <strong>modular way</strong> long before ES6 modules. Each IIFE acted like a <strong>self-contained module</strong>, keeping logic separate and reusable.</p><pre>const Module = (function() {<br>    let privateVar = &quot;I’m private!&quot;;<br>    <br>    return {<br>        getPrivateVar: function() {<br>            return privateVar;<br>        }<br>    };<br>})();<br><br>console.log(Module.getPrivateVar()); // &quot;I&#39;m private!&quot;3. Avoiding Accidental Overwrites</pre><p>JavaScript loads files sequentially. If two scripts define the same function or variable name, the last one wins. IIFEs <strong>shield code from being unintentionally overridden</strong> by later scripts.</p><h3>How IIFEs Improve Performance</h3><p>Another hidden advantage of IIFEs is <strong>faster execution</strong>.</p><p>When JavaScript accesses a variable, it starts looking in the <strong>current scope</strong> and moves outward until it finds it. <strong>Global lookups take longer</strong> than local ones.</p><p>By keeping variables inside an IIFE, the JavaScript engine <strong>avoids unnecessary global scope lookups</strong>, leading to slightly better performance.</p><h3>Do We Still Need IIFEs Today?</h3><p>With ES6 modules (import/export), IIFEs are <strong>less common</strong>, but they still serve a purpose:</p><p>✓ <strong>Working with older JavaScript codebases</strong><br>✓ <strong>Creating self-executing scripts in browsers</strong> (e.g., a tracking script that runs instantly)<br>✓ <strong>Isolating third-party code</strong> from interfering with your scripts<br>✓ <strong>Encapsulating logic in performance-critical applications</strong></p><p>For example, Google Analytics and Facebook Pixel still use <strong>IIFE-based scripts</strong> to ensure their tracking logic runs independently.</p><h3>The Takeaway</h3><p>IIFEs were a <strong>game-changer</strong> for JavaScript developers before ES6 modules, helping keep code <strong>clean, modular, and bug-free</strong>.</p><p>Even today, understanding IIFEs gives you an <strong>edge in debugging, optimizing, and working with legacy code</strong>.</p><p>Next time you encounter one, you’ll know exactly why it’s there — and when to use it yourself!</p><p>If you found this article useful, please press the clap button &amp; follow me for more such in-depth articles related to Web Development. Thank you for reading. See you in the next one :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60de101b907d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Scope for Cleaner, Bug-Free JavaScript]]></title>
            <link>https://medium.com/@akhilgoyals/mastering-scope-for-cleaner-bug-free-javascript-aee7ae080825?source=rss-19e4cfb47283------2</link>
            <guid isPermaLink="false">https://medium.com/p/aee7ae080825</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Akhil Goyal]]></dc:creator>
            <pubDate>Tue, 18 Feb 2025 11:05:00 GMT</pubDate>
            <atom:updated>2025-02-18T11:05:00.679Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HVwcotbUwu70BF6Q8NSraw.jpeg" /></figure><p>Ever spent hours debugging JavaScript, only to realize your variable wasn’t accessible where you thought it would be?</p><p>That’s <strong>scope</strong> in action — the hidden rulebook that decides which variables can be accessed where. Whether you’re a beginner or a seasoned coder, understanding scope is <strong>non-negotiable</strong> if you want to write clean, efficient, and bug-free code.</p><p>Let’s break it down in <strong>simple, everyday terms</strong> so it finally clicks.</p><h3>1. Global Scope (The VIP Pass)</h3><p>If a variable is declared outside any function, it lives in the <strong>global scope</strong>. That means any function, anywhere in your code, can access it.</p><p><strong>Think of it as a public post — everyone can see it.</strong></p><pre>let x = 10;  <br><br>function printX() {  <br>  console.log(x); // No problem, x is global  <br>}  <br>printX(); // 10</pre><p>Sounds great, right? Well, <strong>too many global variables can clutter your code and cause conflicts</strong>, so use them wisely.</p><h3>2. Local Scope (The Private Chat)</h3><p>Variables declared <strong>inside a function</strong> are locked away in their own world. Nothing outside can touch them.</p><p><strong>It’s like sending a DM — only the recipient sees it.</strong></p><pre>function secretFunction() {  <br>  let secret = &quot;Shh!&quot;;  <br>  console.log(secret);  <br>}  <br><br>secretFunction(); // Works fine  <br>console.log(secret); // ❌ ReferenceError: secret is not defined</pre><p>This helps <strong>avoid accidental overwrites and makes debugging easier</strong>.</p><h3>3. Lexical Scope (The Family Tree of Variables)</h3><p>JavaScript follows <strong>lexical (or static) scope</strong>, meaning a function can access variables from its parent scope — but the parent <strong>can’t</strong> access the child’s variables.</p><p><strong>Think of it like a family business: the child inherits knowledge from the parent, but the parent doesn’t inherit from the child.</strong></p><pre>function outer() {  <br><br>  let parentVar = &quot;I&#39;m the parent&quot;;  <br><br>function inner() {  <br>    console.log(parentVar); // Works fine  <br>  }  <br><br>  inner();  <br><br>}  <br><br>outer(); // Logs: &quot;I&#39;m the parent&quot;  <br>console.log(parentVar); // ❌ ReferenceError</pre><p>This ensures <strong>organized, structured code</strong> where child functions can reuse variables without polluting the global space.</p><h3>4. Scope Chain (The Search Party)</h3><p>When a function needs a variable, it doesn’t just give up if it’s not inside its local scope. Instead, <strong>it starts searching up the chain</strong> — first in its parent function, then in the global scope.</p><p><strong>It’s like losing your keys — you check your pockets, then your desk, then the whole house.</strong></p><pre>let a = &quot;global&quot;; <br><br>function parent() {  <br><br>  let b = &quot;parent&quot;;  <br><br>  function child() {  <br>    console.log(a, b); // Finds both in parent/global scope  <br>  }  <br><br>  child(); <br> <br>}  <br><br>parent(); // Logs: &quot;global parent&quot; </pre><p>Understanding this can help you <strong>avoid accidental overwrites and unexpected behavior</strong>.</p><h3>5. Reference Errors vs Undefined (Why Some Variables Misbehave)</h3><p>Two common issues pop up when dealing with scope:</p><h4>Undefined:</h4><p>The variable exists, but has no value yet.</p><pre>let myVar;  <br>console.log(myVar); // ✅ undefined</pre><h4>ReferenceError:</h4><p>The variable doesn’t exist at all.</p><pre>console.log(myVar); // ❌ ReferenceError: myVar is not defined</pre><p>Knowing the difference can <strong>save you hours of debugging frustration</strong>.</p><h3>Conclusion</h3><p>Scope isn’t just a technical detail — it’s the foundation of how JavaScript organizes and protects your variables. Whether you’re debugging errors, optimizing performance, or just trying to keep your code readable, a solid grasp of scope will make you a <strong>stronger, more confident developer</strong>.</p><p>Here’s what to remember:<br>✓ <strong>Global scope</strong> is accessible everywhere — but use it sparingly.<br>✓ <strong>Local scope</strong> keeps things private and avoids conflicts.<br>✓ <strong>Lexical scope</strong> lets functions inherit variables from their parents.<br>✓ <strong>The scope chain</strong> ensures JavaScript finds what it needs.</p><p>The more you practice, the more intuitive it becomes. <strong>Master scope, and you’ll write cleaner, smarter, and more efficient JavaScript. </strong>If you found this article useful, please click the <strong>clap</strong> button &amp; <strong>follow</strong> me for more such <strong>web development</strong> related in-depth articles. Thank you :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aee7ae080825" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Runtime Explained (Without the Confusion)]]></title>
            <link>https://medium.com/@akhilgoyals/javascript-runtime-explained-without-the-confusion-835607f06cd1?source=rss-19e4cfb47283------2</link>
            <guid isPermaLink="false">https://medium.com/p/835607f06cd1</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Akhil Goyal]]></dc:creator>
            <pubDate>Mon, 17 Feb 2025 11:11:49 GMT</pubDate>
            <atom:updated>2025-02-17T11:11:49.921Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OAGFUMH5IR8BxNzHhI2Juw.gif" /></figure><p>If you’ve ever wondered how JavaScript, a <strong>single-threaded</strong> language, manages to handle multiple tasks at once — like making API calls, waiting for user clicks, and running animations — you’re not alone.</p><p>At first glance, JavaScript seems to execute code <strong>line by line</strong> in a strict, synchronous manner. But modern applications require handling asynchronous tasks, and that’s where the <strong>JavaScript Runtime</strong> comes in.</p><p>Understanding this is key to writing better, more efficient code.</p><p>Let’s break it down in a simple, human way. No jargon overload.</p><h3>What Makes Up the JavaScript Runtime?</h3><p>The <strong>JavaScript runtime</strong> is an environment where your JavaScript code executes. It consists of several key components:</p><ol><li><strong>JavaScript Engine</strong> — The heart of execution (e.g., V8 for Chrome, SpiderMonkey for Firefox).</li><li><strong>Call Stack</strong> — Executes synchronous JavaScript code, one function at a time.</li><li><strong>Web APIs</strong> — Provided by the browser to handle tasks like setTimeout, fetch, and event listeners.</li><li><strong>Callback Queue</strong> — Holds completed asynchronous tasks, waiting for their turn to run.</li><li><strong>Event Loop</strong> — The mastermind that decides which task runs next.</li></ol><p>Together, these components allow JavaScript to appear <strong>multi-tasking</strong>, even though it runs on a single thread.</p><h3>Web APIs</h3><p>JavaScript doesn’t natively support asynchronous execution — it relies on <strong>Web APIs</strong> to handle it for us. Think of them as background workers that manage long-running tasks.</p><p>Here are some examples of Web APIs:</p><ul><li>setTimeout() and setInterval() – Schedule functions to run later.</li><li>fetch() – Handles HTTP requests without freezing the page.</li><li>DOM Events — Listens for user actions like clicks and keypresses.</li><li>IndexedDB &amp; LocalStorage — Stores data in the browser.</li></ul><p>These APIs <strong>offload tasks</strong> so the main thread (the Call Stack) doesn’t get blocked, keeping the app responsive.</p><h3>The Call Stack (Where Execution Happens)</h3><p>The <strong>call stack</strong> is a <strong>Last In, First Out (LIFO)</strong> structure that tracks function calls.</p><p>Example:</p><pre>function greet() {<br>  console.log(&quot;Hello!&quot;);<br>}<br><br>greet();</pre><p>Execution:</p><ol><li>greet() is pushed onto the stack.</li><li>console.log(&quot;Hello!&quot;) runs.</li><li>greet() is popped off the stack.</li></ol><p>Simple, right? But what happens when we introduce <strong>asynchronous functions</strong>?</p><h3>The Event Loop (JavaScript’s Traffic Controller)</h3><p>JavaScript needs a way to decide <strong>when</strong> to execute delayed tasks. That’s where the <strong>event loop</strong> comes in.</p><p>The event loop continuously checks:</p><ul><li>Is the <strong>call stack empty</strong>?</li><li>Are there any pending tasks in the <strong>callback queue</strong>?</li><li>If yes, it moves the first task from the queue to the call stack.</li></ul><h3>Example with setTimeout():</h3><pre>console.log(&quot;Start&quot;);<br><br>setTimeout(() =&gt; {<br>  console.log(&quot;Async task complete&quot;);<br>}, 2000);<br><br>console.log(&quot;End&quot;);</pre><h4>Execution Order:</h4><ol><li>console.log(&quot;Start&quot;) → Runs immediately.</li><li>setTimeout() → Sent to Web API (does not block execution).</li><li>console.log(&quot;End&quot;) → Runs next.</li><li>After 2 seconds, the <strong>callback</strong> (console.log(&quot;Async task complete&quot;)) moves from the queue to the stack and executes.</li></ol><h4>Output:</h4><pre>Start<br>End<br>Async task complete</pre><p>This is why asynchronous tasks <strong>don’t pause execution</strong> — they run when JavaScript is ready for them!</p><h3>The Microtask Queue (Even Faster Than Callbacks)</h3><p>JavaScript also has a <strong>microtask queue</strong>, which is even <strong>higher priority</strong> than the callback queue.</p><p>Microtasks include:</p><ul><li><strong>Promises</strong> (.then(), .catch(), .finally())</li><li><strong>MutationObserver API</strong> (used for detecting DOM changes)</li></ul><h3>Example:</h3><pre>console.log(&quot;Start&quot;);<br><br>setTimeout(() =&gt; console.log(&quot;Timeout&quot;), 0);<br><br>Promise.resolve().then(() =&gt; console.log(&quot;Promise resolved&quot;));<br><br>console.log(&quot;End&quot;);</pre><h4>Output:</h4><pre>Start<br>End<br>Promise resolved<br>Timeout</pre><h4>Why?</h4><ol><li>&quot;Start&quot; and &quot;End&quot; run first.</li><li><strong>Promises</strong> (microtasks) execute <strong>before</strong> setTimeout() (callbacks).</li></ol><p>This priority system ensures important tasks (like resolved promises) don’t wait too long.</p><h3>What This Entails</h3><p>JavaScript’s asynchronous execution model, powered by <strong>the event loop, callback queue, and microtask queue</strong>, makes it efficient at handling multiple tasks <strong>without blocking the main thread</strong>.</p><h3>Why This Matters:</h3><ul><li><strong>Faster, non-blocking code</strong> → Your apps stay smooth and responsive.</li><li><strong>Better handling of async operations</strong> → No confusing delays!</li><li><strong>Avoid callback hell</strong> → Use Promises and async/await effectively.</li></ul><h3>Final Takeaway</h3><p>If you truly understand <strong>how JavaScript executes code</strong>, you’ll write cleaner, more efficient applications. So next time something doesn’t execute in the order you expect, you’ll know exactly why!</p><p>If you found this article helpful, please press the clap button &amp; follow me for more such in-depth articles around Web Development. Thank you for reading, see you in the next one :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=835607f06cd1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>