<?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 Jaouadirabeb on Medium]]></title>
        <description><![CDATA[Stories by Jaouadirabeb on Medium]]></description>
        <link>https://medium.com/@jaouadirabeb?source=rss-10c3d28f5898------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*GZYysn7czfQi9YYQ.jpg</url>
            <title>Stories by Jaouadirabeb on Medium</title>
            <link>https://medium.com/@jaouadirabeb?source=rss-10c3d28f5898------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 18:06:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jaouadirabeb/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Understanding Angular Routing : The Modern Approach with Standalone Components]]></title>
            <link>https://medium.com/@jaouadirabeb/understanding-angular-routing-the-modern-approach-with-standalone-components-f3f5d2e20591?source=rss-10c3d28f5898------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3f5d2e20591</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-routing]]></category>
            <dc:creator><![CDATA[Jaouadirabeb]]></dc:creator>
            <pubDate>Wed, 12 Nov 2025 20:40:16 GMT</pubDate>
            <atom:updated>2025-11-12T20:40:16.235Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Angular Routing : The Modern Approach with Standalone Components</h3><p>In Angular, applications are built as <strong>Single Page Applications (SPAs)</strong>.<br> This means that the server serves only one main HTML file, typically index.html. Once it’s loaded, <strong>Angular takes control of the routing on the client side</strong>, dynamically updating the view without reloading the entire page.</p><p>The <strong>Angular Router</strong> listens to changes in the URL and displays the corresponding components for each route, all happening in the browser.<br> As a result, only parts of the page change dynamically, providing a <strong>faster and smoother user experience</strong>.</p><h4>Enable Routing</h4><p>In recent versions of Angular, especially with the introduction of standalone components, we enable routing using the provideRouter() function instead of importing the traditional RouterModule.forRoot().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*w__bndqL1EBAoUlORqMncg.png" /></figure><p>• provideRouter() is part of Angular’s standalone API, introduced to simplify app setup.<br> • We define our routes in a separate file and then provide them in the main.ts file using provideRouter(routes) inside the providers array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*G3Hqo8p_7YGjJqX3SSNYnA.png" /></figure><p>In standalone Angular applications, it’s considered a best practice to keep all global providers and app-wide configurations in a separate file , usually called app.config.ts.<br>In this file, we define an ApplicationConfig object where we include things like routing, HTTP client configuration.<br>This keeps the main.ts file clean and makes the application easier to maintain and test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*r00rq7PdPzCQFh4S7kwWMg.png" /></figure><h4>Rendering Route</h4><p>In Angular, we use the &lt;router-outlet&gt; directive inside the main component’s template , usually in app.component.html , to tell Angular where to render the routed components.<br>When a user navigates to a specific route, the Angular Router looks at the route configuration and dynamically loads the corresponding component into the &lt;router-outlet&gt;.</p><p>So basically, the &lt;router-outlet&gt; acts as a <strong>placeholder</strong> that Angular fills with the component that matches the current route.</p><p>You must <strong>explicitly import</strong> RouterOutlet in the component that uses it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*KFQeJ2xz6ougNlSNEefOxg.png" /></figure><p>Routes are evaluated from top to bottom in the order they are defined in the Routes array.</p><p>The router checks each route sequentially and uses the first match it finds.</p><h4>RouterLink Directive</h4><p>In Angular, we should never use the standard HTML href attribute for internal navigation, because it triggers a full page reload, the browser sends a new request to the server and reloads the entire application.</p><p>Instead, Angular provides the routerLink directive, which updates the URL and tells the Angular Router to load the corresponding component without refreshing the page (without leaving the Single Page Application).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*l9qbYnrFfHJF6_QfrrAVAg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*X-nuosu9zd69MaYlyNQ71w.png" /></figure><p>The routerLinkActive directive is used to add or remove CSS classes to an element based on whether its associated route is currently active.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*M3RMc4aa5C-6VDr9uDte8Q.png" /></figure><p>The routerLink directive in Angular allows us to define routes not only as simple strings but also as arrays, which can include both static route segments and dynamic variables.<br>When we pass an array, Angular automatically joins the parts with slashes (/), so we don’t have to worry about adding them manually.</p><h4>Handling dynamic route parameters with input</h4><p>In the latest versions of Angular (v17+), we can extract dynamic values from routes using component inputs instead of injecting ActivatedRoute.</p><p>Angular’s router can now bind route parameters directly to component inputs, which makes the code cleaner and more declarative.</p><p>To use this feature, we define an input property in the component , for example userId = input.required&lt;string&gt;().<br>When binding route parameters directly to component inputs using input.required&lt;T&gt;(), the name of the input property in the component must match the dynamic variable name in the route.<br>To use Angular’s input-based route parameter binding, we need to tell the router to provide route values as component inputs.<br>This is done using the withComponentInputBinding() function when setting up the router in the application configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*q6FDvcMPrrunGW6Qq6TFgA.png" /></figure><h4>Handling dynamic route parameters with observables</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9xz1mf8LyNevkaAkWo0sHw.png" /></figure><p>ActivatedRoute gives access to route parameters, query parameters, and other info about the current route.<br>paramMap is an observable that emits whenever route parameters change.</p><h4>Child routes</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*aAFJp8IuZnlrkwvf8F-eag.png" /></figure><p>If you have child routes, the parent component template must include a &lt;router-outlet&gt; so that Angular knows where to render the child components.<br>The URL for a child route is concatenated with the parent path:<br> • Parent path: /parent<br> • Child path: child1<br> • Full URL: /parent/child1</p><p>When you’re inside a parent route’s component, you can use relative links to navigate to child routes, without needing to explicitly include the parent’s path in the URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*R5OFplDNBdYCWVsI1hmzGA.png" /></figure><p>By default in Angular Router, child routes do not automatically inherit the route parameters (like id) from their parent routes.<br>You need to explicitly enable this behavior if you want all child routes to have access to their parent parameters.<br>Solution — paramsInheritanceStrategy: ‘always’ <br>When you define your ApplicationConfig with provideRouter, you can pass router options (like paramsInheritanceStrategy) using withRouterConfig().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*sTTNWSihoy48oqbI-7iyuQ.png" /></figure><p>With paramsInheritanceStrategy: ‘always’: All activated child routes will inherit parent route parameters and query parameters.</p><p><strong>NB :</strong> Using a relative routerLink with ../ lets you navigate up one level in the route hierarchy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*M36JnxnrusKRl1Di7LJkQA.png" /></figure><p>Inside a Component (<strong>Programmatic Navigation</strong>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*GVWGF7fwjkuBM19jlwcOMw.png" /></figure><p>When you navigate programmatically, Angular adds a new entry to the browser’s history stack.<br>So pressing the Back button would take you back to the previous URL.<br>If instead, you want to replace the current URL in the browser history (so Back won’t return to the previous route), you use: replaceUrl: true.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*wnOkOGPdWcid0tOnt80gNg.png" /></figure><h4>catch-all route</h4><ul><li>The “**” route matches any URL that hasn’t been matched by a previous route.<br> • It must always be the last route in your route configuration, because Angular evaluates routes in order.<br> • Useful for showing a 404 page, redirecting, or logging invalid URLs.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*S2GO09dGzHk75jmwVuyKYw.png" /></figure><p>redirectTo defines the target path.<br>Angular’s router changes the URL in the browser without reloading the page, and loads the target component instead.<br>Visiting /users/u1 redirects to /users/u1/tasks</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*GgIfNScGw_K4n1-rsKTrBA.png" /></figure><p>When you use pathMatch: ‘full’, Angular requires the entire URL to match exactly the route’s path, there must be nothing extra after it.</p><p>If you forget pathMatch: ‘full’ for empty path redirects (path: ‘’), Angular can enter an infinite redirect loop.</p><h4>Split Routes by Feature</h4><p>When your app grows, having everything in one big app.route.ts becomes messy. <br>It becomes hard to read and maintain.</p><p>Solution : You can define <strong>feature-specific route files</strong> and then <strong>import them</strong> into your main route configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*qF9FMPzEqV99lrgPqGst3g.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3f5d2e20591" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding HTTP Requests and Error Handling in Angular]]></title>
            <link>https://medium.com/@jaouadirabeb/understanding-http-requests-and-error-handling-in-angular-bb7819642b4e?source=rss-10c3d28f5898------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb7819642b4e</guid>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Jaouadirabeb]]></dc:creator>
            <pubDate>Wed, 12 Nov 2025 20:37:27 GMT</pubDate>
            <atom:updated>2025-11-12T20:37:27.225Z</atom:updated>
            <content:encoded><![CDATA[<h4>Configuring the Provider</h4><p>When working with <strong>NgModules</strong> (as opposed to standalone components), instead of configuring the HTTP client in main.ts with :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*Gp6rS6n0-7i7yvAZbpE-dQ.png" /></figure><p>you add it to the providers array of your root NgModule.</p><h4>Injecting HttpClient</h4><p>Once HttpClient is provided, you can inject it into a component or service using Angular’s dependency injection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*yvxGxnuQnY6wC_XwPNmOkw.png" /></figure><h4>Behavior of Observables returned by HttpClient</h4><p>The observables returned by HttpClient:<br> • Emit only one value, which is typically the response body, and<br> • Complete immediately after emitting that single value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EBQNGKeIYAYga5MptNMOHQ.png" /></figure><p>It’s a good practice to specify the type of the response data instead of using any or Object.<br>-&gt; This improves type safety and autocompletion.</p><h4>Configuring an HttpRequest</h4><p>You can customize how the request behaves by passing options to methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GmzbnaM8Hv4aut4DguDeYQ.png" /></figure><h4>Observing Events</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k7oe1ChOPR0jnoMhD0Eicw.png" /></figure><p>The observable will emit multiple values representing different stages of the HTTP request lifecycle (upload progress, response received, etc.).</p><h4>Loading fallback</h4><p>Using complete for a loading fallback : You can manage loading states (e.g., showing a spinner while the request runs) like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gOSZ1Kd_zxBAIG-g0JwQBA.png" /></figure><p>For HttpClient, complete runs only once , right after the next (successful response), if an error occurs, error is called instead, and complete is not triggered.<br>Using complete guarantees code that runs once when the observable completes.</p><h4>Handling HTTP Error</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*vHHDy87QcKNIu2gzpz4xMQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_0TpFSil5gSyd_AqnuulLg.png" /></figure><p>catchError() catches the error, lets you handle or transform it, and optionally rethrows a new one with throwError().</p><h4>Sending data to backend</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*QUk4LfbZcs1l9KlrqnR3aw.png" /></figure><p>Shared Logic -&gt; use service</p><h4>Create a Centralized HTTP Service</h4><p>Outsourcing your HTTP request logic into a <strong>dedicated service</strong> keeps components clean, makes your code reusable, testable, and easier to maintain.</p><p>This service will handle all HTTP requests.</p><h4>tap()</h4><p>tap() operator in RxJS lets you perform side effects on the data flowing through an observable , without modifying the data itself.</p><p>The tap() operator can take a full observer object, just like subscribe() does.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*RPg0Xk75rReDkbUH-CZNhw.png" /></figure><h4>Optimistic update</h4><p>An optimistic update means: You update the UI immediately (as if the HTTP request succeeded).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*-JVxnwCySYFuCbLg96swOg.png" /></figure><h4>Handle failures in an optimistic update flow</h4><p>You perform the optimistic UI change first, then you use catchError to rollback the change if the HTTP call fails.</p><p>catchError in RxJS : Intercepts any error emitted by the observable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*QV5S3mPVMf5pqZ809B0ezw.png" /></figure><p>The<strong> .some()</strong> method in JavaScript checks whether at least one element in the array satisfies a given condition.<br> • It returns true if any element matches<br> • It returns false if none match</p><p>A centralized ErrorService lets you handle and log all errors consistently, and keep your data services focused on data.</p><h3>Http Interceptors</h3><p>An HTTP interceptor sits between:<br> • Your app → when it sends a request <br> • The backend → when it returns a response</p><p>So it can:<br> • Inspect or modify the request before it’s sent<br> • Inspect, modify, or handle the response before your code receives it</p><p>You typically use them to:<br> • Add authentication tokens (JWT, API keys)<br> • Log or monitor requests<br> • Modify headers or URLs</p><p>Interceptors are registered when you provide the HttpClient.</p><p>In modern Angular (standalone API style), that happens in main.ts when you call bootstrapApplication().<br>}) : You register your interceptors where you configure the HttpClient provider, typically in main.ts.</p><p>Two Styles of Interceptors: <br> • Old Style: Class-Based Interceptors (Pre-Angular 16) <br>Before Angular 16, interceptors were always classes implementing the HttpInterceptor interface.<br> • New Style :Functional Interceptors (Angular 16+)<br>Angular 16 introduced functional interceptors , much simpler and more lightweight.<br>You just write a function that takes (req, next) and returns an observable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*ZHIY-oo1w0CtqVMqRA6u_Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb7819642b4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Component lifecycle hooks]]></title>
            <link>https://medium.com/@jaouadirabeb/component-lifecycle-hooks-c7c05411bf2b?source=rss-10c3d28f5898------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7c05411bf2b</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-lifecycle-hooks]]></category>
            <dc:creator><![CDATA[Jaouadirabeb]]></dc:creator>
            <pubDate>Tue, 11 Nov 2025 20:23:05 GMT</pubDate>
            <atom:updated>2025-11-11T20:23:05.637Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why keep the constructor lean?</h3><ul><li>The <strong>constructor</strong> should only do <strong>basic class initialization</strong> (like assigning default values to properties).</li><li>Avoid <strong>complex logic</strong>, <strong>DOM access</strong>, or <strong>service calls</strong> here, because the component isn’t fully initialized yet.</li><li>Angular hasn’t set <strong>input properties</strong> or rendered the <strong>template</strong> at this point.</li></ul><h3>ngOnInit</h3><p>A <strong>lifecycle hook</strong> called <strong>after Angular sets input properties</strong> and initializes the component.</p><p><strong>Why implements OnInit is useful</strong></p><ul><li>Type checking : If you declare implements OnInit and mistype ngOnInit, TypeScript will give an error.</li><li>Code clarity</li><li>Best practice</li></ul><h3>ngOnChanges</h3><ul><li>runs when an @Input() property changes.</li><li>Called before ngOnInit and on every change thereafter.</li><li>Use it to react to input changes from a parent component.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*UndopgpxX0O_foiMRSxb2g.png" /></figure><p>Where changes contains the <strong>previous and current values</strong> of inputs.</p><h3>ngDoCheck</h3><p>Lifecycle hook that runs during every change detection cycle in Angular.</p><ul><li>ngOnChanges = reacts to @Input() changes (Angular detects for you).<br> • ngDoCheck = hook into Angular’s change detection mechanism to do your own checking.</li><li>Called every time Angular runs change detection, which can happen very frequently (on events, async tasks, data bindings, etc.).<br> • Lets you implement custom change detection logic (e.g., deep-checking an object/array that Angular wouldn’t detect by default).<br> • But because it runs so often, putting heavy logic inside can cause performance issues.</li></ul><h3>Content VS View</h3><p>• View = component’s own template + declared children.<br> • Content = external stuff projected into the component via &lt;ng-content&gt;.</p><h3>ngAfterContentInit</h3><p>• Called once, after Angular projects external content (&lt;ng-content&gt;) into the component.<br> • At this point, you can safely access @ContentChild / @ContentChildren references.</p><h3>ngAfterContentChecked</h3><p>• Lifecycle hook called after every check of the projected content (content passed into &lt;ng-content&gt;).<br> • Runs after ngAfterContentInit, and then on every change detection cycle if the projected content may have changed.<br> • Useful if you need to react to changes in the projected content.</p><h3>ngAfterViewInit</h3><ul><li>Lifecycle hook from AfterViewInit interface.<br> • Called once after Angular has fully initialized the component’s own view (its template and child components declared inside it).<br> • At this point, you can safely access @ViewChild / @ViewChildren references.</li></ul><h3>ngAfterViewChecked</h3><ul><li>ngAfterViewInit → runs once, when the view is ready.<br> • ngAfterViewChecked → runs after every change detection when the view is re-checked.</li></ul><h3>ngOnDestroy</h3><p>= Cleanup hook</p><p>• Called just before Angular destroys a component or directive.<br> • Ideal for cleanup tasks to avoid memory leaks.</p><p>Common Uses<br> • Unsubscribe from Observables or event subscriptions<br> • Stop timers (setInterval, setTimeout)<br> • Release resources</p><h3><strong>DestroyRef</strong></h3><p>Angular 16 introduces DestroyRef for flexible, automatic cleanup.</p><p>Lets you register cleanup callbacks instead of implementing OnDestroy.</p><p>inject(DestroyRef) -&gt; Provides a reference to the component’s or directive’s destroy lifecycle.</p><blockquote>Callback = a function you give to Angular to execute later.<br>Tree-shakable = unused code can be safely removed at build time.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*kcDNY9fN_lsfHqTgAF2L7A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*svQYi2sSEe1odXPOBs_fLw.png" /></figure><h3>afterRender and afterNextRender</h3><p><strong>Angular 16</strong> introduced afterRender and afterNextRender as new lifecycle hooks that run <strong>after </strong>Angular completes change detection.</p><p>This ensures that your code runs after the browser has finished painting the UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*kmtsuKthvg8DPLZ-g1tPYA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*Rtp65KH09gbSx5HKfa1c0A.png" /></figure><p>⚠ Performance sensitive : runs very frequently<br>⚠ Not for modifying component state (can cause infinite loops)</p><p>These hooks are particularly useful for:<br> • Analytics and monitoring<br> • DOM measurements<br> • Performance tracking<br> • Debugging complex change detection scenarios</p><h3>The Execution Sequence</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*FvstowOSN4u1_PIKfnJRhA.png" /></figure><h4>DOM Readiness</h4><ul><li>ngOnInit() : DOM <strong>Not ready</strong><br> • ngAfterViewInit() : DOM <strong>Ready but might change</strong><br> • afterRender() : DOM, Final state for this cycle</li></ul><h3>Signals + Effects for Change Tracking</h3><h4>effect</h4><p>An <strong>effect</strong> is a <em>reactive function</em> that runs automatically whenever one of the signals it reads changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*wHmUKDJCkqwYlvpluBGjQQ.png" /></figure><p><strong>Key Benefits of onCleanup</strong></p><ol><li>Prevents Memory Leaks : Automatically cleans up resources</li><li>Avoids Race Conditions : Cancels previous operations</li><li>Better Performance : Stops unnecessary work</li><li>Cleaner Code : All cleanup logic in one place</li><li>Automatic Management : No manual lifecycle hook handling</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*DJdxl78oMkNZhH9YLJiiFg.png" /></figure><h3>FormsModule</h3><p>When you want to use ngSubmit on a form in Angular, you need to import the FormsModule (or ReactiveFormsModule if you’re using reactive forms).</p><p>ngSubmit is part of Angular’s FormsModule. Without it, Angular doesn’t recognize [(ngModel)], ngForm, or ngSubmit directives.</p><h3>Template Variables</h3><ul><li>Declared with #varName.</li><li>Scope: only available within that template.</li><li>You use the hashtag # only when declaring the variable.<br>After that, you refer to it without #.</li><li>When attached to a <strong>native HTML element</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*a66z-JCwdCYj-qFqaIeskQ.png" /></figure><p>#titleInput refers to the <strong>DOM element</strong> itself → an instance of HTMLInputElement</p><ul><li>When attached to a <strong>custom Angular component</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*CDS2n37K1JkV9Dh8CtVASw.png" /></figure><p>#childComp refers to the instance of the ChildComponent class, not an HTML element.</p><h3>@ViewChild</h3><p>It allows you to <strong>interact with the DOM or component instance directly, </strong>typically after the view has been initialized.</p><p>selector → can be a <strong>template variable name (string)</strong> or a <strong>component/directive class</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*AvDXYo96WUreu-7AN3EIzA.png" /></figure><blockquote>Use ? if the element might not always exist.</blockquote><blockquote>Use ! when it’s guaranteed to exist and you access it after ngAfterViewInit().</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*mN6PXyhIJmDiYFhX0XO0vw.png" /></figure><blockquote>console.log() : Displays DOM elements as they appear in the page.</blockquote><blockquote>console.dir() : Displays an interactive list of the object’s properties, the JavaScript object structure itself.<br>Useful for inspecting the internal properties of DOM elements or objects.</blockquote><h4>New viewChild() function (signal-based)</h4><p>In Angular <strong>17.3 or newer</strong>, a new signal-based alternative to @ViewChild / @ViewChildren has been introduced.</p><p>The return type of viewChild(…) is Signal&lt;T | undefined&gt; (when not required) or Signal&lt;T&gt; (when using .required)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*Z8CKs5Ew-JUrtuJ7PYqKxg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*1uDhRL6JYfbcsFB2GDCq0Q.png" /></figure><h4>@ViewChildren</h4><p>Similar to @ViewChild, but instead of selecting one element/component/directive,<br>it selects all matching elements in the component’s view.</p><ul><li><strong>ViewChild does NOT see content projected via &lt;ng-content&gt; </strong>because projected content belongs to the <strong>host component’s template</strong>, not the child component’s view.</li></ul><h3>@ContentChild</h3><p>Is used to get a reference to projected content, the content passed from the parent into &lt;ng-content&gt;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*tSHlzcepX0l4X_NRySjmpw.png" /></figure><h4>New contentChild() function (signal-based)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X0-rcipL7Rl97eV-mC_F2w.png" /></figure><h3>Template For Loops</h3><p>Using Angular 17 or later</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*U-bw02I8I4lmX7jPJno_zA.png" /></figure><p><strong>Contextual variables available in Angular’s @for loop</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*FLaCAWFwBKwc2jRdYoX0vw.png" /></figure><ul><li>$index is 0-based — first item has index 0<br>Type-safe — TypeScript knows the types automatically</li></ul><p><strong>Using Signals to manage status/state is a modern and efficient approach in Angular.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*ehV2hMWfNZfDlG9tE6sLfA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*hA2sN8BXK2kzvm5mYne58A.png" /></figure><p>The map() method is an array function in JavaScript.<br>It creates a new array by applying a function to each element of the original array.<br>Take each element, transform it, and return the new transformed array.</p><p>{ …ticket } → copies all key-value pairs from ticket<br>status: ‘closed’ → overwrites the status property with ‘closed’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*wedvn8oyQ_Zs7KyoEb3Emw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*reg_KrkUBTYjJ9LNqo-fBg.png" /></figure><p>The { alias: ‘data’ } option means:<br>In the parent component’s template, this input will be bound using the name data instead of ticket.</p><blockquote>Using Aliases Is <em>Not Recommended</em></blockquote><p><strong>The transform Option</strong><br>The transform option lets you automatically modify (or normalize) the input value before Angular assigns it to your signal.<br>It’s kind of like a “preprocessor” for your input.</p><p>Example : Convert String to Number</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*A7oVD6Eq8rEtHZvcn_vvJQ.png" /></figure><h3>Two Way Binding</h3><p>Angular’s two-way binding [(x)] looks for :<br> • an Input named x<br> • an Output named xChange</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*PE4B4O1YJDBmQ2M2R8l9WA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*AQLGTU3FLJo_cwhOTUDSOw.png" /></figure><p>The parent and child share a single source of truth, and changes in one reflect in the other.</p><p><strong>Using Angular 17.2 or later</strong></p><p><strong>model()</strong></p><p>model() replaces the old @Input() + @Output() combo.<br>It automatically creates a reactive signal input/output pair with the same name, so you can do</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*sUBfnb3q_dM2OITKAWUVig.png" /></figure><p>without needing a sizeChange output.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7c05411bf2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Zone.js to Zoneless : The Evolution of Angular’s Change Detection, Signals, and Observables]]></title>
            <link>https://medium.com/@jaouadirabeb/from-zone-js-to-zoneless-the-evolution-of-angulars-change-detection-signals-and-observables-ded49b9e664a?source=rss-10c3d28f5898------2</link>
            <guid isPermaLink="false">https://medium.com/p/ded49b9e664a</guid>
            <category><![CDATA[angular-change-detection]]></category>
            <category><![CDATA[angular-signals]]></category>
            <category><![CDATA[rxjs-observables]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Jaouadirabeb]]></dc:creator>
            <pubDate>Tue, 11 Nov 2025 20:20:26 GMT</pubDate>
            <atom:updated>2025-11-11T20:20:26.417Z</atom:updated>
            <content:encoded><![CDATA[<h3>From Zone.js to Zoneless : The Evolution of Angular’s Change Detection, Signals, and Observables</h3><h3>What is Change Detection</h3><p>Process of detecting data changes and updating the view to keep the UI consistent with component data.<br>Triggered by events, async calls, or manually</p><h3>Double change detection</h3><p>When your Angular app runs in development mode, Angular runs change detection twice for every component check.</p><ul><li>1st run → detects and updates bindings normally</li><li>2nd run → immediately re-runs detection to verify that nothing changed after the first run</li></ul><p>If any value changes between the two runs, Angular throws the famous : <strong>ExpressionChangedAfterItHasBeenCheckedError</strong></p><h4>How to Disable It</h4><p>You can disable the double-checking behavior by running Angular in <strong>production mode</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*-RR_E16FRzAjZ3xnHfc25A.png" /></figure><h3>Angular Change Detection Mechanism</h3><h3>How Angular Uses Zone.js</h3><ol><li>When your app runs, Angular creates an <strong>NgZone</strong> that wraps the whole app.</li><li>Any async event (like a click, HTTP response, timer, etc.) happens <strong>inside this zone</strong>.</li><li>Zone.js intercepts the event and <strong>notifies Angular</strong> when it’s done.</li><li>Angular’s <strong>change detection</strong> is triggered automatically.</li></ol><h3>Avoid Zone Pollution / Opting Out of Change Detection</h3><p><strong>-&gt; Avoiding unnecessary Zone.js tracking</strong> for events that <strong>don’t matter to Angular’s UI updates</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*uRj81fHqrFVG06pqm9miDw.png" /></figure><p>If code has no effect, Angular gives you <strong>fine-grained control</strong> over change detection and Zone.js integration.<br> You can either <strong>opt out of automatic change detection</strong> or <strong>opt out of Zone.js watch mode </strong>entirely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*k-tm3xXG4JpuCTak_43XCw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*VVSPChDwI5NYszRkk7pnpA.png" /></figure><p>This optimisation can avoid unecessary change detetcion.</p><h3>OnPush Strategy</h3><p>When you set a component’s change detection strategy to OnPush, Angular becomes <strong>smarter and more selective</strong> about when to check it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*8ABn8oMAqnbbe7t4c8aIHg.png" /></figure><p>Only check this component (and its subtree) if there’s a clear reason to — don’t run change detection every time the parent changes.</p><h4>When Angular Triggers Change Detection for OnPush Components</h4><ul><li>Input reference changes</li><li>Event originates inside component : A DOM event (click, input, etc.) happens within the component or its children.</li><li>Manual change detection</li></ul><h3>Change Detection &amp; Signals</h3><p>With <strong>Signals</strong>, Angular knows exactly what data changed and which components depend on it, so it can update <strong>only those components</strong> — even under OnPush.</p><h3>RxJS &amp; OnPush</h3><p>Variables ending with $ (like messages$) indicate that the variable is an Observable (or Subject / BehaviorSubject).<br> It’s a naming convention.</p><p>A BehaviorSubject is both an Observable and an Observer — meaning you can:<br> • Subscribe to it<br> • Emit new values with .next()</p><p>When subscribing manually to an Observable (e.g., in ngOnInit), Angular doesn’t automatically know that your component’s data has changed.</p><p>will not trigger a UI update under OnPush — unless you tell Angular manually.<br>You fix this by calling markForCheck() inside the subscription:<br>markForCheck() tells Angular that this component (and ancestors using OnPush) should be checked in the next change detection cycle.</p><p>When you manually subscribe to an observable in a component, you must also unsubscribe when the component is destroyed.<br>Modern Angular (v16+) — DestroyRef : It lets you easily run cleanup logic without implementing OnDestroy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*OIdQvtDb83_NxjsN3mLs6Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/895/1*yEObwf5z53gMDpQqxQvlNw.png" /></figure><ul><li>When you combine <strong>OnPush</strong>, <strong>RxJS subscriptions</strong>, and <strong>ChangeDetectorRef</strong>, you end up with a lot of repetitive boilerplate.</li></ul><p><strong>-&gt; Alternative </strong>: use <strong>async pipe</strong> in the template</p><h3>Async Pipe</h3><p>The async pipe in Angular automatically subscribes to an Observable or Promise, updates the view when new values are emitted, and unsubscribes when the component is destroyed. It simplifies code, prevents memory leaks, and works perfectly with OnPush change detection.<br>Under the hood, Angular handles everything for you:<br>• It subscribes to your Observable<br>• Renders the latest emitted value<br>• Triggers change detection (even with OnPush)<br>• And automatically unsubscribes when the component is destroyed<br>So you don’t need to use ChangeDetectorRef, DestroyRef, or ngOnDestroy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*ZjrJ1CT4dopVmN906zSYbg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*GGq0NhaHIyhALAbtO_6EGg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*AmKwZ-HSgFA-17thjkSBIQ.png" /></figure><h3>Zoneless</h3><p>In Angular with signals, when you change a signal’s value, Angular automatically knows that the state has changed and updates the relevant views — no need for zone.js to trigger change detection.<br> That’s why signals make it possible to build <strong>zoneless Angular applications</strong>, improving performance and reducing overhead.</p><h4>Remove Zone.js from your project</h4><ul><li>Remove zone.js from angular.json file</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*DvZ3JXmuI88DVTmPL3cMjw.png" /></figure><ul><li>Enable Zoneless change detection : In your main.ts, add the new Angular provider.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*3wF49a6OIU5CoV8udgVMog.png" /></figure><ul><li>Restart your dev server</li><li>&gt; Your app will now run without zone.js, relying on Signals for precise change detection.</li></ul><h3>Observable</h3><p>An <strong>Observable</strong> is an RxJS object that emits a stream of data over time. It allows Angular apps to handle asynchronous operations like HTTP calls or events reactively.</p><p>RxJS provides multiple ways to create Observables — for example, using interval(), which emits values automatically over time , or using a Subject, which can emit values manually through its next() method.</p><p>For all Observables, you need to subscribe in order to start receiving emitted values.<br>When an Observable emits data, it calls the next() method, and when it finishes, it calls complete().</p><p><strong>Operators </strong>in RxJS are functions that allow you to transform, filter, or combine the values emitted by an Observable — for example, map(), filter().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*uQcaxEgmOSAZKc52k5M5HQ.png" /></figure><p>.pipe() lets you apply one or more RxJS operators in sequence to process the values emitted by an Observable.</p><h3>Observable VS Signals</h3><p>Observables represent values over time — they emit a stream of values asynchronously, and you subscribe to react to those emissions.<br>Signals are value containers — they hold a current value and automatically notify Angular when that value changes, enabling precise and synchronous change detection.<br>You can read the value of a Signal directly without subscribing — just by calling it like a function.<br>Observables are better suited for handling asynchronous events or data streams — like HTTP requests, user interactions, or timers.<br>Signals are great for managing application state because they hold and track the latest value automatically.</p><h3>Converting Signals to Observables</h3><p>You can listen to a signal’s changes without using an effect by converting it to an Observable with toObservable() function from @angular/core/rxjs-interop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*vjIuCwspp6cDgo-cFxLJKg.png" /></figure><h3>Observable to Signals</h3><p>You can convert an Observable into a Signal using the toSignal() function from @angular/core/rxjs-interop and then bind it directly in the template (HTML) — no subscription or async pipe needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*ztZZyGz5qHcA-PuUFCaFSg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*QaYTLyHNiNZT6_GwImf09g.png" /></figure><p>Observables, unlike Signals, don’t have an initial value — they start emitting only when data becomes available.<br>When you convert an Observable to a Signal using toSignal(), Angular assigns an initial value of undefined by default, because the Observable hasn’t emitted yet.<br>You can override this by providing an initial value as the second argument to toSignal().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*6Z2H4zgnFKo7N5Iw767-tQ.png" /></figure><h3>Creating Custom Observable</h3><p>• When creating an Observable → you define <strong>when to emit</strong> values.<br> • When subscribing → you define <strong>how to handle</strong> those values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*Ygddt9koxo-VC3QpsMpMfQ.png" /></figure><p>When creating a custom Observable, the subscriber object provides three main methods:<br> • next(value) <br> • error(err) <br> • complete()</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ded49b9e664a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Forms Deep Dive : Template-Driven vs Reactive Approaches]]></title>
            <link>https://medium.com/@jaouadirabeb/angular-forms-deep-dive-template-driven-vs-reactive-approaches-84b981fb988f?source=rss-10c3d28f5898------2</link>
            <guid isPermaLink="false">https://medium.com/p/84b981fb988f</guid>
            <category><![CDATA[template-driven-form]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[reactive-forms]]></category>
            <dc:creator><![CDATA[Jaouadirabeb]]></dc:creator>
            <pubDate>Tue, 11 Nov 2025 20:18:55 GMT</pubDate>
            <atom:updated>2025-11-11T20:18:55.283Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular Forms Deep Dive : Template-Driven vs Reactive Approaches</h3><p>Angular provides <strong>two main ways to handle forms</strong>:</p><ol><li><strong>Template-Driven Forms</strong> : simpler, managed mostly in the template.</li><li><strong>Reactive Forms</strong> : more control in the component class, better for complex logic.</li></ol><h3>Template-Driven Forms</h3><p>Template-Driven Forms are Angular’s declarative approach to form handling where:<br> • Form logic resides primarily in the template<br> • Uses directives like ngForm, ngModel<br> • Ideal for simple forms and rapid development<br> • Implementing complex logic or dynamic validation can be more challenging than with reactive forms.</p><p>• #form=”ngForm” creates template reference to NgForm instance<br> • ngModel registers the control<br> • name attribute is mandatory for control registration</p><h4>Submitting and Accessing Form Values</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*HqnmABLDAf59dgk6fXJHPQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*oGOFI5xFFu-FXnXFFv5XAQ.png" /></figure><h4>Form Validation in Template-Driven Forms</h4><p>Angular automatically manages validation directives like:<br> • required<br> • email<br> • minlength<br>These directives register validation rules with Angular but don’t block form submission automatically, they just mark the control invalid.<br>Angular also adds CSS classes such as:<br> • ng-valid, ng-invalid<br> • ng-touched, ng-untouched<br> • ng-dirty, ng-pristine</p><h4>Accessing and Listening to Template-Driven Form Values in Angular (without Form Submission)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*7gfeA4HyubbBsJPWTa3rig.png" /></figure><p>• viewChild.required&lt;NgForm&gt;(“form”) gets a signal pointing to the NgForm instance in the template (referenced by #form) (This is the new Angular v17+ signal-based ViewChild API).</p><p>• afterNextRender() is used to run code after the component and its template have finished rendering.<br> • (Otherwise, this.form() would be undefined since the template isn’t ready yet.)</p><p>• this.form().valueChanges is an Observable that emits every time a form control changes.</p><ul><li>You can listen to live form value updates.<br> • You don’t need to wait for form submission.<br> • You can get the current values at any moment</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*dU4JsYRQ6dheR8pgDpdKhQ.png" /></figure><ul><li>debounceTime(500) -&gt; wait 500 milliseconds after the last emitted value before continuing<br> • form.valueChanges -&gt; Angular emits a new value on every keystroke.<br> • debounceTime helps reduce the frequency of these updates.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*xIQwIgCM7pJHuOxxz8dtLw.png" /></figure><h4>Accessing NgForm.controls Too Early</h4><p>When using template-driven forms, the form (NgForm) instance is created after Angular initializes the view, but its internal controls are registered a little bit later, once each ngModel directive is linked to its input.<br>So when you do something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*iFTgq4i6GVb1KQ_wGCMwsQ.png" /></figure><p>That’s because:<br> • The &lt;form&gt; is rendered <br> • But the child inputs with ngModel haven’t yet registered themselves with NgForm</p><h4>Workaround: Using setTimeout</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*u02-mkZZkeNTYwz1Vp71Ew.png" /></figure><p>The Better Solution : Use Reactive Forms</p><h3>Reactive Forms</h3><p>Reactive forms are <strong>set up and managed entirely in TypeScript.</strong></p><p>This approach makes <strong>complex, dynamic, and large forms</strong> easier to handle, test, and maintain</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*4Bb-o1zahxNq0VB45Pz6iw.png" /></figure><h4>Bind the Form to the Template</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*AQp1qUkcXXj9U9MLaFUYXg.png" /></figure><p><strong>Shortcut:</strong> Using formControlName Directly</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*JLMnBBrCjwk6WhLE9fT5xg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*XcKo1_Rr1UZTN0ZuXGwuJQ.png" /></figure><h4>Form Submission</h4><p>In Reactive Forms, the form model (the FormGroup and its controls) is fully defined in your TypeScript class.<br>This means:<br> • You know exactly what controls exist.<br> • You can access their values directly.</p><p>You don’t need to rely on template reference variables like #form=”ngForm”.<br> • In Reactive Forms, this.form.value returns a typed object that exactly matches your form structure. Without needing to access through nested properties like form.form.value (as in template-driven forms).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*F2wM0jzzgQjVeQAnwF65Pg.png" /></figure><h4>Form Validation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*X--gCBtrRfKYQ1nPF4bhug.png" /></figure><p>Using form.controls.email repeatedly makes the template long and hard to read.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4xzsnVbXaQAuQuRLsyWvlQ.png" /></figure><p>The cleaner way is to use Angular’s <strong>get()</strong> method to access the control directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VNQJNfd1brW1p4mEBuNT-g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*SOdiaEzaOQXB0keRMEUxSA.png" /></figure><h4>Custom Validator</h4><p>A validator is simply a function that takes an AbstractControl as an argument and returns either:<br> • null if the control’s value is valid, or<br> • an error object if it’s invalid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*JyhZFSAQRtJ8sY2I3Ec4eA.png" /></figure><h4>Async Validator</h4><p>An async validator is a function that:<br>takes a control (AbstractControl)<br>returns an Observable of either:<br> • null (valid)<br> • or an error object<br>It’s used when validation depends on an external source, like a backend API.<br>Example Email Uniqueness Validator</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*g9twnf58F1z2MPTOo4qfag.png" /></figure><p><strong>NB :</strong> console.log(“Code before @Component”) runs as soon as the module is loaded, not when the component is instantiated. That means it executes only<strong> once</strong> when Angular first loads the file, not each time the component is created.</p><h4>Nested forms</h4><p>In Reactive Forms, when your data has a hierarchical structure (like an object with nested fields), you can use nested FormGroups or even FormArrays to organize your form logically.</p><p><strong>Nested FormGroups</strong><br>You use formGroupName=”address” in the template to tell Angular that the nested inputs belong to the inner group.<br>When you call this.form.reset(), it will reset everything recursively, including nested groups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*4qjQSdenChGCK5vAxqixBQ.png" /></figure><p><strong>Nested FormArray</strong><br>A FormArray is used when you have a list of similar form controls — for example :<br> • a list of phone numbers <br> • a list of addresses <br> • or a list of items in an order</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vlt6zCzHELxGD8jl0RJSVw.png" /></figure><p>While a FormGroup represents an object (key–value structure),<br>a FormArray represents a list (array).</p><ul><li>Controls are connected by numeric indexes starting at 0</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*N7ZmLtV9a_XXPhyymIqZFg.png" /></figure><h4>FormGroup with a Validator</h4><p>A FormGroup can take a second parameter for validators.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*KN9tcRNcSHHferHD8I-tvQ.png" /></figure><p>A FormGroup has a controls property, which is an object containing all child controls.</p><h4>Factory Function for Validators</h4><p>A validator factory is a function that returns a validator, allowing you to pass parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*1A8MwQEOZx8BkUz12Vbetg.png" /></figure><p>If you have nested groups or arrays, accessing them directly can get messy or require type casting.<br>The recommended way is to use<strong> form.get().</strong></p><p><strong>Why Use Factory Validators</strong><br> • Parameterized : lets you create dynamic rules<br> • Reusable : you can pass different arguments for different controls<br> • Works with sync or async validators</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84b981fb988f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Angular Component Patterns : Projection, Slots, Host, and Class Binding]]></title>
            <link>https://medium.com/@jaouadirabeb/advanced-angular-component-patterns-projection-slots-host-and-class-binding-155c5985180c?source=rss-10c3d28f5898------2</link>
            <guid isPermaLink="false">https://medium.com/p/155c5985180c</guid>
            <category><![CDATA[angular-contentprojection]]></category>
            <category><![CDATA[slot]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Jaouadirabeb]]></dc:creator>
            <pubDate>Mon, 10 Nov 2025 19:58:27 GMT</pubDate>
            <atom:updated>2025-11-10T19:58:27.389Z</atom:updated>
            <content:encoded><![CDATA[<h3>Advanced Angular Component Patterns : Projection, Slots, Host, and Class Binding</h3><p>When building Angular applications, components are the building blocks. As apps grow, structuring these components well becomes crucial for maintainability and flexibility. This article explores advanced Angular component patterns, like content projection, multiple slots, and extending native elements , that help you write cleaner, reusable, and more scalable code.</p><h3>Separation of Concerns</h3><p><strong>When to split a component into multiple components?</strong><br>The main guiding principle is Separation of Concerns :</p><ul><li>Each component should have a single, clear responsibility.</li><li>Each component should only do <strong>one thing well</strong>.</li></ul><blockquote>If a component has more than one reason to change, split it.</blockquote><p><strong>But… don’t overdo it</strong><br>Splitting everything can lead to :<br> • Too many tiny components → hard to navigate<br> • Boilerplate overhead (imports, selectors, etc.).</p><p>So it’s always a balance :<br> • Small/simple app → bigger components are fine.<br> • Large/complex app → finer-grained components are crucial for maintainability.</p><h3>Component Projection</h3><pre>import { Component, input } from &#39;@angular/core&#39;;<br>@Component({<br>  selector: &#39;app-child&#39;,<br>  standalone: true,<br>  templateUrl: &#39;./child.component.html&#39;<br>})<br>export class ChildComponent {<br>  message = input&lt;string&gt;();<br>}<br></pre><pre>&lt;div class=&quot;child&quot;&gt;<br>  &lt;h2&gt;{{ message() }}&lt;/h2&gt;<br>&lt;!-- No ng-content here --&gt;<br>&lt;/div&gt;</pre><pre>&lt;app-child message=&quot;Hello from parent&quot;&gt;<br>  &lt;p&gt;This paragraph is inside the tags&lt;/p&gt;<br>  &lt;button&gt;Click me&lt;/button&gt;<br>&lt;/app-child&gt;</pre><p>• The &lt;h2&gt; renders correctly: Hello from parent.<br> • The &lt;p&gt; and &lt;button&gt; are completely ignored , Angular doesn’t know where to put them.<br> • Result : only &lt;h2&gt; shows, everything inside &lt;app-child&gt; … &lt;/app-child&gt; is gone.<br><strong>Solution : Content Projection</strong><br>-&gt; It’s the mechanism that lets you pass content from a parent component<strong> into a child component’s template</strong>.<br> This way, the child decides <strong>where</strong> to render the parent’s content.</p><pre>&lt;div class=&quot;child&quot;&gt;<br>  &lt;h2&gt;{{ message() }}&lt;/h2&gt;</pre><pre>  &lt;!-- This is where the content from parent will appear --&gt;<br>  &lt;ng-content&gt;&lt;/ng-content&gt;<br>&lt;/div&gt;</pre><blockquote>Any content inside a custom component’s tags is ignored by default.<br>To render it, the child must use &lt;ng-content&gt; somewhere in its template.</blockquote><h4>Content projection with multiple slots</h4><p>This is Angular’s way of letting a parent component pass in different pieces of content into <em>different parts</em> of the child’s template.</p><p><strong>Select</strong></p><ul><li>&lt;ng-content&gt; without select = default slot (catches everything not matched by another slot).<br> • &lt;ng-content select=”[attr]”&gt; = projects only elements with that attribute.<br> • select=”h2&quot; → only &lt;h2&gt; tags.<br> • select=”.highlight” → only elements with class highlight.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*oF3CQkf1SKyMzKz6dak-_g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*NWlOSv6eV-XNQHJT0HxT9g.png" /></figure><ul><li>You can specify multiple selectors <br>You can also do this for component selectors</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*xH-_dRvkxW-a_5cj_qm-yQ.png" /></figure><p><strong>ngProjectAs</strong></p><p>ngProjectAs is used in content projection when you want Angular to treat an element as though it matched a different selector.</p><p>In other words : It forces Angular to project a piece of content into the &lt;ng-content&gt; slot that matches another selector.</p><p>Why it’s useful : Sometimes the element you want to project doesn’t naturally match the select query of &lt;ng-content&gt;.<br>Instead of changing the element’s attributes or structure, you can apply ngProjectAs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*DwOUTT-5XH-flsoASr2qwg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*qgmQj-8IaqnjiUqm7vjR7g.png" /></figure><p><strong>Fallback content</strong></p><p>Is any HTML inside &lt;ng-content&gt;.</p><ul><li>Before Angular v15 → fallback inside &lt;ng-content&gt; was ignored.</li><li>From Angular v15 onward → you can put fallback content directly inside &lt;ng-content&gt;.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*fDSo1GzbgVFC4piBv4QDkQ.png" /></figure><ul><li>If the parent projects an &lt;icon&gt; element → that gets displayed.</li><li>If nothing is projected → Angular renders the fallback (→).</li></ul><h3>Element selectors/attribute selectors</h3><h4>Normal custom component (element selector)</h4><pre>@Component({<br>  selector: &#39;app-button&#39;,<br>  template: `&lt;button&gt;&lt;ng-content&gt;&lt;/ng-content&gt;&lt;/button&gt;`<br>})<br>export class AppButtonComponent {}</pre><pre>&lt;app-button&gt;Save&lt;/app-button&gt;</pre><ul><li>In the DOM :</li></ul><pre>&lt;app-button&gt;<br>  &lt;button&gt;Save&lt;/button&gt;<br>&lt;/app-button&gt;</pre><p>So you get a custom element (&lt;app-button&gt;) wrapping a native &lt;button&gt;.<br>This is not what you want.</p><h4>Attribute selector extending a built-in element</h4><pre>@Component({<br>  selector: &#39;button[appButton]&#39;, // attach component to a native &lt;button&gt;<br>  template: `&lt;ng-content&gt;&lt;/ng-content&gt;`,<br>  styleUrls: [&#39;./app-button.component.css&#39;],<br>  standalone: true<br>})<br>export class AppButtonComponent {}</pre><ul><li>Usage</li></ul><pre>&lt;button appButton&gt;Save&lt;/button&gt;</pre><ul><li>In the DOM</li></ul><pre>&lt;button appbutton=&quot;&quot; class=&quot;...&quot;&gt;Save&lt;/button&gt;</pre><p>No wrapper, no &lt;app-button&gt; tag, it stays a native &lt;button&gt;, but now Angular associates it with your component logic.</p><blockquote>By using an attribute selector with a native element type, you <strong>extend the built-in element </strong>instead of wrapping it.</blockquote><p>when we say extend a built-in element, it means :<br> • Keep the native element (&lt;button&gt;, &lt;input&gt;, etc.).<br> • Attach Angular component or directive behavior via an attribute selector.</p><h3>View Encapsulation</h3><p>By default, Angular applies styles from a component only to that component’s template. This is called <strong>View Encapsulation</strong>, and it prevents styles from leaking across components.</p><p>Angular provides three modes:</p><p><strong>Emulated (default)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*iHFdepkJJUDLYEnEPyumXg.png" /></figure><ul><li>Angular rewrites your CSS selectors with unique attributes so they apply only to the component.</li></ul><p><strong>ShadowDom</strong></p><ul><li>Uses the browser’s native Shadow DOM.<br>The <strong>browser’s native Shadow DOM</strong> = a feature of modern browsers that lets elements hide their internal DOM and CSS inside a special, isolated <strong>shadow-root</strong>.</li><li>Styles are fully scoped to the component and won’t affect anything outside.</li></ul><p><strong>None</strong></p><ul><li>No encapsulation: styles are global and affect the entire application.</li></ul><h3>Styling the Host Element with :host</h3><p>Every component has a host element.</p><p>Every Angular component is rendered as a custom HTML tag, called the host element. The :host selector lets you style this element directly. Unlike regular CSS, where you target tags or classes in your template, :host applies styles to the component’s own tag-even though it never appears inside the component’s HTML.</p><p>Example :</p><pre>@Component({<br>  selector: &#39;app-card&#39;,<br>  template: `<br>    &lt;div class=&quot;box&quot;&gt;<br>      &lt;ng-content&gt;&lt;/ng-content&gt;<br>    &lt;/div&gt;<br>  `,<br>  styleUrls: [&#39;./card.component.css&#39;]<br>})<br>export class CardComponent {}</pre><p>If you use it like this :</p><pre>&lt;app-card&gt;<br>  &lt;p class=&quot;highlight&quot;&gt;Hello World&lt;/p&gt;<br>&lt;/app-card&gt;</pre><p>The &lt;p&gt; goes inside &lt;ng-content&gt;. You can style it with normal CSS in your global styles.<br>So: projected content = styling what goes inside.</p><pre>:host {<br>  display: block;<br>  border: 1px solid #ccc;<br>}</pre><p>This is about styling the &lt;app-card&gt; tag itself (the wrapper around everything inside).<br>This affects &lt;app-card&gt; directly, not its children.</p><p>Together<br> • &lt;ng-content&gt; gives you control of the inside (the projected children).<br> • :host gives you control of the outside (the component wrapper tag).</p><p>That’s why I said together they give full control :<br> • Inside = projected slot content<br> • Outside = the wrapper element</p><h4>What happens with ViewEncapsulation.None</h4><p>When you set : encapsulation: ViewEncapsulation.None -&gt; Angular does not scope your CSS anymore — it just injects it as global CSS.<br>At that point, :host has no special meaning → your styles won’t apply.</p><p>The workaround is to give your component a <strong>class (or id)</strong> on its host element, then target it directly in global CSS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*c5kht2yDjgiK7copukKR2w.png" /></figure><h4><strong>Add a class automatically</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*5uJnUG2gyHBBb-T9T6r8eA.png" /></figure><p>With host: { … }, you avoid :<br> • Manually adding classes in the HTML<br> • Forgetting attributes</p><p>Instead of wrapping your content in an extra &lt;div&gt; just to apply a class or attribute, you can <strong>style the component’s own host element</strong> directly. This keeps your template cleaner and avoids unnecessary DOM nodes.</p><h3>@HostBinding</h3><p>When you use @HostBinding(‘propertyName’), Angular automatically adds or updates that property/attribute/class/style on the host element,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*8gHQ6Cp4Jr9je6Rez20tqA.png" /></figure><h3>@HostListener</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*5DTbCylNEanVG2xH55mapg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*nPaOJuJlc1zCsJ0yzAZbFg.png" /></figure><h3>ElementRef</h3><ul><li>It’s a wrapper around a native DOM element in Angular.</li><li>Angular gives you an ElementRef when you inject it, pointing to the <strong>host element</strong> of your directive or component.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*v8OCt3bR1UDC73v8b9lTDA.png" /></figure><h3>Class Binding with Object Literal</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*UC_ilntpxRTsuQoZGEMrcQ.png" /></figure><h3>Conclusion</h3><p>Mastering these patterns gives you more control over how components interact and how content is displayed. Use them wisely : split components only when it adds clarity, leverage content projection for flexibility, and extend native elements when you want both Angular power and native behavior. These techniques make your Angular applications easier to maintain, more reusable, and future-proof.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=155c5985180c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Dependency Injection : Services, Tokens, and Best Practices]]></title>
            <link>https://medium.com/@jaouadirabeb/angular-dependency-injection-services-tokens-and-best-practices-8499fe09aeff?source=rss-10c3d28f5898------2</link>
            <guid isPermaLink="false">https://medium.com/p/8499fe09aeff</guid>
            <category><![CDATA[angular-services]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Jaouadirabeb]]></dc:creator>
            <pubDate>Mon, 10 Nov 2025 19:52:16 GMT</pubDate>
            <atom:updated>2025-11-10T19:52:16.523Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular Dependency Injection : Services, Tokens, and Best Practices</h3><h3><strong>Services</strong></h3><p><strong>Services</strong> allow you to share <strong>data and functionality</strong> across different parts of an application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*1RH1rIWjOYeVMWoWnmCj_A.png" /></figure><h3>Creating an Injectable service</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*WgneS4IR7J9fiRIcWtsX3g.png" /></figure><h3>Dependency Injection</h3><p><strong>Dependency Injection (DI)</strong> allows you to <strong>request instances of services from Angular</strong> instead of creating them manually.</p><h4>Injecting services using Constructor / inject()</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*HuiAIyZJC7-ebY7VgJmUVA.png" /></figure><p>The inject method takes a token, which corresponds to the name of the service class.<br>Angular dependency injection hierarchy</p><h3>Injector Hierarchy</h3><p>Angular uses <strong>multiple injectors</strong> to manage where and how services can be registered.</p><p>To make a class or value <strong>injectable</strong>, Angular must be aware of it. This is done by <strong>registering it with an injector</strong>, allowing Angular to provide it whenever it is requested.</p><p>Angular organizes injectors in a <strong>hierarchy</strong> to manage how dependencies (services, tokens, etc.) are shared across the application. When a dependency is requested, Angular first looks in the <strong>nearest injector</strong> and then moves <strong>up the hierarchy</strong> until it finds the requested provider. If no matching provider is found, Angular throws an error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*Gq1b8xB_UobPo1JazqAA-Q.png" /></figure><h4>PlatformInjector</h4><ul><li>The top-level injector in Angular.</li><li>Created when the Angular platform is initialized (before any app modules).</li></ul><h4>Root Injector</h4><ul><li>Created when the root module (AppModule) is bootstrapped.</li><li>It’s the main injector for your app.</li><li>Services here are <strong>singletons, </strong>one instance shared across the whole app.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*bDhgEWdcw-buSIky8ovC-Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*nFvQ3P7j30wpLI4mlTxtCg.png" /></figure><ul><li>Services listed in providers are registered with the root injector.</li><li>They behave like services provided with providedIn: root.</li></ul><h4>Module Injector</h4><ul><li>Created when Angular loads a feature module (like UserModule, AdminModule, etc.).</li><li>Used when the module has its own providers.</li></ul><h4>ElementInjector</h4><ul><li>Created for each component or directive in the component tree.</li><li><strong>All child components and directives</strong> in the subtree of that component <strong>have access</strong> to the services provided here, unless a child overrides it with its own provider.</li><li>It stores providers defined directly in that component :</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*pTUimy2tD5mWIqsFbMaEhQ.png" /></figure><p>When a dependency is requested inside a component, Angular first checks that component’s <strong>ElementInjector</strong>.</p><ul><li>When a service is provided in a component’s providers array, Angular creates a <strong>new instance </strong>of that service for each component instance.</li><li>This is different from root-level services, which are <strong>singletons </strong>shared across the entire app.</li></ul><h4>NullInjector</h4><ul><li>The <strong>final stop</strong> in the injector hierarchy.</li><li>If Angular reaches the NullInjector and still can’t find the requested dependency, it <strong>throws an error</strong>:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*U0lkW3149xABr0HIohHK1g.png" /></figure><h4>Example lookup flow<br>Suppose a component requests a service :</h4><ol><li>Angular checks the component’s <strong>ElementInjector (component-level)</strong>.</li><li>If not found, it goes up to parent components.</li><li>Then to any <strong>ModuleInjector</strong> <strong>(module-level), </strong>Only relevant if the component belongs to a module that provides the service.</li><li>Then to the <strong>Root Injector</strong>.</li><li>Finally, if not found, the <strong>NullInjector</strong> throws an error.</li></ol><h4>Issue with services in bootstrapApplication()</h4><ul><li>When you declare a service in the providers array of bootstrapApplication(), it’s registered in the root injector.</li><li>Root-level services are eagerly instantiated (or at least included in the initial bundle).</li><li>This means even if a component or feature never uses the service, the code for that service is still loaded.</li></ul><h3>Inject services into other services</h3><ul><li>You can inject one service into another because both are managed by the root injector.</li><li>However, you cannot inject a service provided via an ElementInjector into another service.</li><li>This is because :<br>- Services are not part of the component tree or DOM, so they don’t have access to component-level injectors.<br>- The ElementInjector hierarchy only applies to components and directives, not standalone services.</li></ul><h3>Exploring the Injection Tree</h3><p>You can <strong>see Angular’s injection hierarchy in action</strong> using <strong>Angular DevTools</strong>.<br> The <strong>Injectables tab</strong> (also called the <em>Dependency Injection Tree</em>) allows you to <strong>browse through the injector hierarchy</strong> and see <strong>which services are registered where, </strong>whether at the component (ElementInjector), module, or root level.</p><p>This is a great way to <strong>debug or understand</strong> how Angular resolves dependencies and which injector provides a given service.</p><h3>Custom DI Token</h3><p>By default, the name of token equal the name of class service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WKfpWo6GBijjR-VPt1Q9Dw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*S9wlaJFYtVdbmTnFS8FmgA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*SRZZg6WinX9cmVRQwPB2jA.png" /></figure><h3>Inject <strong>Values / Constants</strong></h3><p>You can provide <strong>non-class values</strong> using InjectionToken :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EaWHWnVUvsal4aGDm8euEA.png" /></figure><p>Angular uses this token to <strong>inject the array anywhere it’s needed</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*L2q2hmbabpAkjyXKVGUddw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*dCLlK9-TpXal5EzJUQeO2Q.png" /></figure><ul><li>Defines a type → TaskStatusOptions</li><li>Creates a token → TASK_STATUS_OPTIONS</li><li>Provides a constant array → TaskStatusOptions</li><li>Exposes a provider object → TaskStatusOptionsProvider</li></ul><p>-&gt; This pattern makes it type-safe, reusable, and injectable anywhere in the Angular app.</p><h3>Best Practices</h3><h4><strong>Use the spread operator to maintain immutability</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*l0KyuyOyxHdg23eSBOWbGw.png" /></figure><p>Here you’re using the spread operator (…) to create a new copy of the oldTasks array, then you add newTask to it.</p><p>Why creating a copy is beneficial<br>Immutability : Avoids mutating the existing state</p><p>If you did this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*5Fbv8AIEc6-hJeaIj-2F1Q.png" /></figure><p>you would modify the original array in place, this is a mutation.<br>That can cause problems because many frameworks (like Angular Signals, React state, or NgRx) detect changes by comparing references.</p><p>By creating a new array, you ensure:<br> • A new reference is created.<br> • The framework detects that the state actually changed.<br> • UI updates correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E7n5mdIrTtqYVlhBZQ2mxQ.png" /></figure><h4>Always create new objects instead of modifying existing ones</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/1*P_HZgKXX-MwykeAq46Vgsw.png" /></figure><p>The map() function creates a new array, and { …task, status: newStatus } creates a new task object, ensuring immutability throughout the update process.</p><h4>Prefer read-only signals for safety and separation</h4><p>Prefer using <strong>read-only signals</strong> instead of <strong>writable signals, </strong>this ensures a clear separation between the layer that manages your data and the one that consumes it.<br> Make the tasks signal private and expose a <strong>read-only signal</strong> instead, this guarantees that the task list cannot be accidentally modified from other components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*Z-fSyMCxlTAv_TaX4Z1INA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8499fe09aeff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Angular Directives & Pipes : From Built-in Features to Custom Structural Logic]]></title>
            <link>https://medium.com/@jaouadirabeb/mastering-angular-directives-pipes-from-built-in-features-to-custom-structural-logic-6b699505615f?source=rss-10c3d28f5898------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b699505615f</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-directive]]></category>
            <category><![CDATA[angular-pipe]]></category>
            <dc:creator><![CDATA[Jaouadirabeb]]></dc:creator>
            <pubDate>Sun, 09 Nov 2025 16:20:28 GMT</pubDate>
            <atom:updated>2025-11-09T16:20:28.929Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Angular Directives &amp; Pipes : From Built-in Features to Custom Structural Logic</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*VHkoLF-09xn6i0HfD8OLJw.png" /></figure><h3>Directives VS Componnets</h3><p><strong>Directives</strong> are used to enhance existing elements by adding extra behavior or functionality to them.<br> For example, the built-in ngModel directive can be added to an input element to make Angular aware of its value and state.</p><p>Unlike components, <strong>directives do not have their own templates</strong> , they simply extend or modify the behavior of existing DOM elements.</p><p><strong>Components</strong>, on the other hand, are <strong>directives with an associated template</strong>. They control a section of the UI and define how it should look and behave.</p><h3>Built-in Directives</h3><p>Built-in directives are the directives that come predefined with Angular. They provide common functionalities that developers can use directly without creating custom directives.</p><p>Angular’s built-in directives fall into two main categories:<br> • Attribute Directives <br> • Structural Directives</p><h3>Attribute Directives</h3><p>The ngModel directive is a good example of an attribute directive.<br>Attribute directives are used to add behavior or modify the appearance of existing elements.</p><p><strong>Examples :</strong><br> • ngModel — For instance, ngModel enables features like two-way data binding and dynamically managed CSS classes such as ng-dirty, ng-touched, and ng-pristine, which reflect the state of the form control.<br>You apply it as an attribute to an existing element, which is why it’s called an attribute directive.<br> • ngClass : Dynamically adds or removes CSS classes.<br> • ngStyle : Dynamically sets inline styles.</p><p><strong>NB :</strong> <br> • ng-pristine : The control has not been changed by the user yet.<br> • ng-dirty : The control’s value has been modified.<br> • ng-untouched : The control has not lost focus yet.<br> • ng-touched : The control has lost focus (the user has interacted with it).<br> • ng-valid : The control’s value is valid according to its validation rules.<br> • ng-invalid : The control’s value is invalid.</p><h3>Structural Directives</h3><ul><li>Structural directives are used to change the structure of the DOM, for example by adding, removing, or manipulating elements dynamically.</li><li>A common example is <strong>*ngIf</strong>, which conditionally adds or removes elements from the DOM based on a given expression, *ngFor and *ngSwitch.</li><li>In modern Angular applications (Angular 15+ with standalone components), you need to import structural directives like NgIf explicitly in your component’s imports array.</li><li>In standalone components, structural directives such as NgIf, NgFor and others are <strong>not automatically available, </strong>you must import them explicitly from @angular/common.</li></ul><h3>Building Custom Attribute Directive</h3><p>A custom directive in Angular is defined using the @Directive() decorator.<br>It lets you attach custom behavior to DOM elements and extend their functionality.<br>The selector of a directive usually uses square brackets ([]) to indicate that it matches elements carrying a specific <strong>attribute</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*_Q85C6l7fr5VsW5CP7v4WA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*CEIjyTGnp_0bAFUHoNuzcA.png" /></figure><ul><li>The @Input() decorator allows your directive to receive data from the template.<br> • The host property declaratively binds DOM events (like mouseenter and mouseleave) and properties (like style.backgroundColor) to class members.<br> • When passing a string literal, you don’t need brackets</li></ul><h3>Dependency Injection in Directives</h3><p>Just like components, <strong>directives can use dependency injection</strong> to access Angular services or interact directly with the element they are attached to.<br> One common use case is to <strong>inject the host DOM element</strong> to manipulate it directly.</p><h4>Injecting the Host Element</h4><p>To access the element on which the directive is applied, you can inject ElementRef from @angular/core.<br>It gives you a direct reference to the native DOM element.</p><ul><li>The inject() function (available since Angular 14) is a modern alternative to injecting dependencies through the constructor.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*ijyXO-i6QsJmddWP-9eMTA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*6hRGjAIko0n1XX5YB76KBw.png" /></figure><h3>Building Custom Structural Directive</h3><h4>TemplateRef vs ElementRef</h4><p>When building custom directives or working with templates, Angular provides two important references to interact with the DOM: TemplateRef and ElementRef.</p><p><strong>ElementRef</strong><br> • Represents a direct reference to a DOM element.<br> • Allows you to read or modify the element directly (e.g., change styles, classes, or attributes).<br> • Typically injected into attribute directives.</p><p><strong>TemplateRef</strong><br> • Represents an Angular template (&lt;ng-template&gt;), not a concrete DOM element.<br> • Allows you to programmatically instantiate or render template content.<br> • Typically used in structural directives to control the addition/removal of DOM content.</p><h3>Using ng-template to Wrap Content</h3><p>In Angular, ng-template is a special element that acts as a container for template content that is not rendered by default.<br>It’s commonly used with structural directives like *ngIf, *ngFor, or custom directives.</p><p>• The content inside an ng-template does not appear in the DOM initially.</p><p>• Instead, it exists as a TemplateRef, which is a blueprint of the content that Angular can instantiate when needed.</p><h4>Rendering ng-template with createEmbeddedView</h4><p>To display the content of an ng-template in the DOM, you use:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*L7eB4eVjqJB7q9sPY193zw.png" /></figure><p>• TemplateRef represents the template content inside &lt;ng-template&gt;.<br> • ViewContainerRef represents a location in the DOM where views can be inserted.<br> • createEmbeddedView(templateRef) clones the template and inserts it into the container.</p><p>To <strong>remove it</strong>, you use :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*hALyMmR3VXsRNe-qPlBGmg.png" /></figure><h4>Running Effects in a Structural Directive</h4><p>In a <strong>custom structural directive</strong>, you often want to <strong>react to changes in an input</strong> , for example, updating the DOM whenever a value like userPermission changes.</p><ul><li>You can do this <strong>inside the setter</strong> of the @Input property.</li><li>Using effect() : Angular Signals allow you to <strong>react to changes in a reactive value</strong> declaratively. You can use the effect() function inside a directive to automatically run logic whenever an input changes.</li></ul><h3>Using * with Structural Directives</h3><p>In Angular, structural directives like *ngIf, *ngFor, or your custom directives can be applied using a * prefix instead of wrapping content in an &lt;ng-template&gt;.</p><ul><li>The * syntax is <strong>syntactic sugar</strong> that Angular automatically expands into an &lt;ng-template&gt; under the hood.<br> • It allows you to write cleaner templates without manually creating &lt;ng-template&gt; elements.</li><li>The value after * (here, isVisible) is evaluated dynamically, just like in property binding with square brackets ([]).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*w_-52F_GmIqC6NWzo7kgWg.png" /></figure><h3>Using hostDirectives</h3><p>hostDirectives allow you to reuse a directive’s behavior by attaching it to a component or another directive without modifying the template.<br>This is useful when you want certain functionality applied automatically, without requiring developers to remember to add the directive in HTML.</p><p>How It Works<br> • You define a directive as usual.<br> • In a component (or another directive), you use the hostDirectives property in the metadata to attach the directive.<br> • Angular automatically applies the directive behavior to the host element.</p><p><strong>Key Benefits</strong><br> • Automatic behavior : Reuse directives without requiring template changes.<br> • Cleaner templates : Reduces boilerplate in HTML.<br> • Composable logic : You can attach multiple directives via hostDirectives.</p><h3>Pipes</h3><p>Pipes in Angular are a powerful feature that <strong>transform the way data is displayed</strong> in templates.<br> They allow you to format, filter, or modify values directly in your HTML, keeping your templates clean and declarative.</p><h3>Built-in pipes</h3><p>Angular provides several built-in pipes for common transformations.</p><h4>DatePipe</h4><p>Formats dates according to a specific pattern or locale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*uysm8XLQkRMyNkB6qRF4IA.png" /></figure><p>To use it programmatically : import { DatePipe } from ‘@angular/common’;</p><h4>DecimalPipe</h4><p>Formats numeric values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*tOGPNuIvffVpQvQG4VrUTA.png" /></figure><p>Format : {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}</p><p>• minIntegerDigits: Minimum number of integer digits (default = 1)<br> • minFractionDigits: Minimum number of digits after the decimal (default = 0)<br> • maxFractionDigits: Maximum number of digits after the decimal (default = 3)</p><h3>Creating a Custom Pipe</h3><p>A custom pipe is simply a class annotated with the @Pipe() decorator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*k7NnQgqbZUmSO_hJJio5tA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*OiAh3gtvnSabeSvgHdsdGg.png" /></figure><p><em>Tip :</em><br> You can set default parameter values and let TypeScript infer the return type for more flexibility.</p><h3>Combining Pipes</h3><p>You can chain multiple pipes together:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*qTlaKZWGSIrSJWZGsTcyIA.png" /></figure><p>If your pipe can receive null values, extend its input type accordingly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*-KV8dtqgDTtuLESKsfOEkw.png" /></figure><h3>Performance and Change Detection</h3><p>By default, Angular pipes are <strong>pure</strong>, meaning they re-execute only when the input <strong>reference</strong> changes.</p><p>This works well for primitive values, but can be tricky for <strong>arrays or objects</strong> , since their references stay the same even if their contents change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*HwMx37qcVl5eEwv7adpxjA.png" /></figure><h4>Solution 1: Update the array immutably</h4><p>Reassign a new array to trigger the pipe again.</p><h4>Solution 2: Mark the pipe as impure</h4><p>This disables the caching mechanism, making the pipe re-run whenever anything changes in the template.<br> <strong>Use with caution, </strong>impure pipes can impact performance.</p><h3>Pipes in Angular Control Flow</h3><p>You can use pipes inside Angular’s new control flow blocks like @for.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*gulQNd83XIILFc2naAERjg.png" /></figure><h3>When Not to Use Pipes</h3><p>Avoid using pipes for transformations that affect <strong>element position</strong> (like sorting for display order), especially when the array indices matter.<br> In such cases, handle sorting in your component logic instead.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b699505615f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Content and State Management in Angular : From Interpolation to Signals]]></title>
            <link>https://medium.com/@jaouadirabeb/dynamic-content-and-state-management-in-angular-from-interpolation-to-signals-39379be9544c?source=rss-10c3d28f5898------2</link>
            <guid isPermaLink="false">https://medium.com/p/39379be9544c</guid>
            <category><![CDATA[string-interpolation]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[signal]]></category>
            <dc:creator><![CDATA[Jaouadirabeb]]></dc:creator>
            <pubDate>Sun, 09 Nov 2025 16:04:20 GMT</pubDate>
            <atom:updated>2025-11-09T16:04:20.337Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dynamic Content and State Management in Angular : From Interpolation to Signals</h3><p>Modern web applications are all about dynamic, real-time user interfaces. Angular makes this seamless by providing multiple ways to bind data, listen to user input, and update the state of your app.</p><p>In this article, we’ll explore how Angular handles dynamic content in templates using interpolation, property and attribute binding, and how state management has evolved with the introduction of Signals in Angular 16.</p><h3>Displaying Dynamic Content in Templates</h3><p>Angular templates allow you to render dynamic values in several ways :</p><h4>1. <strong>String Interpolation</strong></h4><p>Use double curly braces {{ }} to display dynamic values directly in the HTML. &lt;p&gt;Hello, {{ username }}!&lt;/p&gt;</p><p>Angular evaluates username and updates the DOM whenever its value changes.</p><h4>2. Property Binding</h4><p>Property binding lets you bind component properties to HTML element properties.</p><pre>&lt;img [src]=&quot;selectedUser.avatar&quot; /&gt;</pre><ul><li>Square brackets [ ] mark the target property on the DOM element.</li><li>Data flows one way, from the component class to the DOM.</li></ul><pre>&lt;img [src]=&quot;My Text Value&quot;&gt; </pre><p>Angular tries to evaluate My Text Value as TypeScript, which is <strong>invalid syntax</strong>, so it fails.</p><p><strong>If you need to bind a fixed string while still using [] </strong>→ wrap the string in quotes inside the expression:</p><pre>&lt;img [src]=&quot;&#39;logo.png&#39;&quot;&gt;</pre><p>Angular evaluates the expression ‘logo.png’ as a string literal.</p><h4>3. Attribute Binding</h4><p>Sometimes, you need to set HTML attributes rather than properties. For this, Angular provides attribute binding:</p><pre>&lt;td [attr.colspan]=&quot;tableSpan&quot;&gt;&lt;/td&gt;</pre><ul><li>Syntax : attr.&lt;attributeName&gt;</li><li>Attributes initialize DOM properties and influence element behavior.</li></ul><h3>Getters for Dynamic Values</h3><p>Instead of binding to plain variables, you can also bind to getters :</p><pre>get imagePath() {<br>return &#39;assets/user.png&#39;;<br>}</pre><p>This approach makes your template bindings cleaner and allows you to compute values on the fly.</p><h3>Listening to User Input</h3><p>Angular makes it easy to react to user events:</p><pre>&lt;button (click)=&quot;onSelectUser()&quot;&gt;Select User&lt;/button&gt;</pre><ul><li>Parentheses ( ) denote an event binding.</li><li>Data flows from the DOM to the component, updating its state.</li></ul><h3>State Management in Angular</h3><p>State refers to the data and UI conditions of your application.</p><p>Traditionally, Angular used Zone.js and its built-in change detection mechanism :</p><ul><li>Zone.js automatically patches browser APIs (events, timers, etc.) and notifies Angular when changes occur.</li><li>Angular then runs change detection and updates the UI accordingly.</li></ul><h3>Signals : A Modern Way to Manage State</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/0*WXBbkxinsZBI7s7s.png" /></figure><p>Since <strong>Angular 16</strong>, a new reactivity model called <strong>Signals</strong> has been introduced.</p><p>A <strong>Signal</strong> is a trackable container that holds a value and notifies Angular whenever that value changes. Angular then updates only the parts of the UI that depend on that signal.</p><h4>Writable signals</h4><pre>import { signal } from &#39;@angular/core&#39;;<br><br>selectedUser = signal&lt;User | null&gt;(null);<br><br>// Update<br>this.selectedUser.set({ id: 1, name: &#39;Alice&#39; });<br><br>// Read<br>console.log(this.selectedUser());</pre><ul><li>Initialize with signal()</li><li>Update with .set() or use the .update() operation to compute a new value from the previous one:</li></ul><pre><br>count.update(value =&gt; value + 1);</pre><ul><li>Read by calling the signal like a function selectedUser()</li></ul><p>This eliminates the need for Zone.js in many scenarios, making Angular faster and more efficient.</p><h4>Computed Signals</h4><p>Computed signals are derived signals whose value is automatically calculated from one or more other signals. They are read-only and always stay in sync with the signals they depend on.</p><pre><br>import { signal, computed } from &#39;@angular/core&#39;;<br><br>const price = signal(100);<br>const quantity = signal(2);<br><br>// Computed signal<br>const total = computed(() =&gt; price() * quantity());<br><br>console.log(total()); // 200<br><br>quantity.set(3);<br>console.log(total()); // 300 (recalculated automatically)</pre><p><strong>Computed signals are not writable signals : </strong>You cannot directly assign values to a computed signal. That is, That’s because its value is derived, not stored.</p><h3>Conclusion</h3><p>Angular provides a rich toolbox for handling dynamic content and state management. From classic features like interpolation and property binding to modern reactive tools like Signals, Angular continues to evolve towards more efficient, predictable, and developer-friendly applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39379be9544c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Standalone Components vs Modules]]></title>
            <link>https://medium.com/@jaouadirabeb/angular-standalone-components-vs-modules-851fc2819b03?source=rss-10c3d28f5898------2</link>
            <guid isPermaLink="false">https://medium.com/p/851fc2819b03</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-state-management]]></category>
            <category><![CDATA[angular-module]]></category>
            <dc:creator><![CDATA[Jaouadirabeb]]></dc:creator>
            <pubDate>Sun, 09 Nov 2025 16:02:09 GMT</pubDate>
            <atom:updated>2025-11-09T16:02:09.789Z</atom:updated>
            <content:encoded><![CDATA[<p>Angular has undergone a major shift with the introduction of standalone components. Traditionally, apps were built entirely with modules, where every component, directive, and pipe had to be declared inside an NgModule. While this ensured consistency, it also added a lot of boilerplate.</p><p>Since Angular 14, standalone components have simplified this model, and from Angular 19, they are now the default way to create components.</p><p>Still, modules haven’t disappeared , they remain useful for grouping and reusing code. The real strength of modern Angular is the ability to combine both approaches seamlessly.</p><p>In this article, we’ll explore the differences between standalone components and modules, and when to choose each.</p><h3>Standalone Components vs Modules</h3><p>Angular supports both module-based and standalone components :</p><ul><li>Modules group components together using @NgModule, declaring components, and importing shared modules.</li><li>Standalone components are self-contained and recommended for modern Angular apps.</li></ul><h3>Standalone Components</h3><p>A standalone component is a self-contained unit in Angular. Unlike traditional components, it doesn’t require an NgModule to declare it. You enable this by adding the standalone: true flag inside the @Component decorator.</p><pre>@Component({<br>selector: &#39;app-root&#39;,<br>standalone: true,<br>imports: [FormsModule],<br>templateUrl: &#39;./app.component.html&#39;<br>})<br>export class AppComponent {}</pre><ul><li>Can directly import other modules (like FormsModule, ReactiveFormsModule,or feature modules).</li><li>Works without being listed inside any NgModule.</li></ul><p><strong>NB :</strong> With the release of <strong>Angular 19, standalone components became the default</strong> for new Angular components. That means that if you DON’T set standalone:false (e.g., if you don&#39;t set standalone at all) inside of @Componnet(), you&#39;ll get a standalone component.</p><h4>Bootstrapping a Standalone Component</h4><ul><li>The entry point of every Angular app is the main.ts file. With standalone components, you can bootstrap your app without a root module:</li><li>You can bootstrap your app with a <strong>standalone component</strong>, no module needed.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*nrPihBbWSked8eIinDHBMA.png" /></figure><ul><li>bootstrapApplication (from @angular/platform-browser) already includes what BrowserModule used to provide, so you don’t need to import BrowserModule in a standalone setup.</li><li>This works only if the root component is standalone. Otherwise, you must bootstrap an Angular module (commonly AppModule) that declares the root component.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*uGwSgnQTq8RaDJjVUnVt2Q.png" /></figure><blockquote>Modules are still useful for grouping components and reusing them. You can combine module-based and standalone components seamlessly.</blockquote><h3>Angular Modules Overview</h3><p>Angular modules organize your app (app.module.ts file) :</p><ul><li><strong>declarations -&gt; </strong>Components, directives, pipes</li><li><strong>imports -&gt; </strong>Other modules or standalone components</li><li><strong>exports -&gt;</strong> Components/directives available to other modules</li><li><strong>bootstrap -&gt; </strong>The root component when bootstrapping the app</li></ul><h4>Important modules</h4><ul><li>BrowserModule, includes Angular’s core directives, pipes, and is imported <strong>only once </strong>in the <strong>root module</strong> (AppModule) . Never import it in feature modules.</li><li>CommonModule , includes common directives like ngIf and ngFor, DatePipe, CurrencyPipe, etc..<br>- Used in feature modules or shared modules.</li></ul><p><strong>What happens if you forget BrowserModule in AppModule?</strong><br>Angular will still compile successfully, because nothing is syntactically wrong. However, at runtime Angular won’t have a renderer for the browser.</p><p>As a result, it doesn’t know how to transform your components into real DOM elements.</p><p>Your &lt;app-root&gt; will remain empty in the HTML page , which is why you’ll just see a blank page in the browser.</p><blockquote>Putting shared components into their <strong>own module</strong> is a common Angular pattern</blockquote><h4>Shared Module</h4><ul><li>A Shared Module is designed to hold reusable components, directives, and pipes.<br> It does not bootstrap any component.<br> Its main purpose is to declare and export these building blocks so they can be used in other modules or standalone components.</li><li>Only export the components, directives, and pipes that you actually want to reuse.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*ujjVt3WjICphHWuvLwmhBg.png" /></figure><h3>Angular DevTools</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*QVRtCu3QSGhcs4Ao_wMpvg.png" /></figure><h4>Key Features</h4><p><strong>Components</strong><br> • View the entire component tree of your app.<br> • Inspect inputs, outputs, and local state of any component.</p><p><strong>Profiler</strong><br> • Lets you record change detection cycles.<br> • You can see which components re-render, how long they took, and optimize performance.</p><p><strong>Injector Tree</strong><br> • Shows the Angular dependency injection graph.<br> • Useful for debugging where services are provided (root, feature module, component level).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=851fc2819b03" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>