<?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 Prince Acquah Darko on Medium]]></title>
        <description><![CDATA[Stories by Prince Acquah Darko on Medium]]></description>
        <link>https://medium.com/@kwamePrince?source=rss-4c912de4952f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*iPGxJ9nsIDKMakweyltLVw.jpeg</url>
            <title>Stories by Prince Acquah Darko on Medium</title>
            <link>https://medium.com/@kwamePrince?source=rss-4c912de4952f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 23:45:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kwamePrince/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[Runtime Config for Angular on Kubernetes — No More Rebuilds Part 2]]></title>
            <link>https://medium.com/@kwamePrince/runtime-config-for-angular-on-kubernetes-no-more-rebuilds-part-2-97d95091d3a8?source=rss-4c912de4952f------2</link>
            <guid isPermaLink="false">https://medium.com/p/97d95091d3a8</guid>
            <dc:creator><![CDATA[Prince Acquah Darko]]></dc:creator>
            <pubDate>Fri, 24 Jul 2026 21:38:19 GMT</pubDate>
            <atom:updated>2026-07-24T21:41:17.554Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Runtime Config for Angular on Kubernetes — No More Rebuilds Part 2</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*1RGWrbkRp8k1-Ad_Doe99A.jpeg" /></figure><p>Welcome back. <a href="https://medium.com/@kwamePrince/runtime-config-for-angular-on-kubernetes-no-more-rebuilds-23d72720fe9e">In Part 1</a> we did all the Angular groundwork and ended up with a tidy, production-ready Docker image running locally — but we also called out the catch: the config was still baked into the image. Change a value, rebuild the image. That’s the whole thing we’re here to fix.</p><p>So in this part we actually fix it. We’ll take that same image — no rebuilding, no changes — push it into a Kubernetes cluster running on Minikube, and instead of shipping env.json inside the image, we’ll serve it from a ConfigMap. Once that’s wired up, changing a config value becomes a job for whoever manages the cluster, not a job for whoever builds the app. Your support team edits a ConfigMap, you don’t touch the image at all.</p><p>I’ll be honest though — getting there wasn’t completely smooth for me, and I think that’s actually the useful part. A few things tripped me up that the tutorials tend to gloss over:</p><p>- Minikube quietly ignoring the image I’d just built locally<br>- Kubernetes refusing to use that local image and trying to pull it from Docker Hub instead<br>- A ConfigMap that has to exist before the thing that uses it<br>- And the big one — editing the config and seeing absolutely nothing change in the browser</p><p>Now let’s move to Minikube to deploy this image. (I’m assuming you have Minikube installed — if not, you can grab it <a href="https://minikube.sigs.k8s.io/docs/start/?arch=%2Fmacos%2Farm64%2Fstable%2Fbinary+download">here</a>.)</p><p>After a successful installation, start Minikube from your local terminal with:</p><pre>minikube start</pre><p>But here’s the first catch: the image only exists locally, so Minikube can’t see it yet. We need to load it into Minikube. (You could also push it to a Docker registry, but I’ll load it directly here.)</p><pre>minikube image load env-demo:latest</pre><p>Now list the images to verify env-demo was loaded:minikube image ls | grep env-demo</p><p>You should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WizdMmJdTDRH-zKFOUeRLA.png" /></figure><p>So now let’s create a namespace and keep all our work in it. (This isn’t strictly required — I just want us to group the project’s resources together.)</p><pre>k create ns env-demo</pre><p><em>Quick note: I’ve set up an alias so that k means kubectl, and the namespace throughout this post is env-demo.</em></p><p>We’ll now create our deployment.yaml file in a declarative way. Start with:</p><pre>k create deployment --help</pre><p>This prints the various ways to create a deployment. (Note: this isn’t a Kubernetes course, so I won’t go step by step from here on. For the next steps you’ll just see me editing the service file and the rest, all created the same declarative way.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rx7vcXgQKQXeimsMw63PjQ.png" /></figure><p>Let’s take the first example and edit it to suit our needs:</p><pre>kubectl create deployment my-dep  --image=busybox --dry-run=client -o yaml &gt; dev.yaml</pre><p>The — dry-run=client flag means it doesn’t actually create anything — it behaves like Angular’s — dry-run=true. The rest just pipes the generated YAML into a dev.yaml file.</p><p>Now let’s open the file with vim and make the necessary changes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*stIYjpSyLNVVORtXsYjPZw.png" /></figure><ul><li>We renamed the labels and name from my-dep to env-demo.</li><li>We set the image to our local env-demo:latest.</li><li>And we mounted the ConfigMap as a volume — that’s the whole magic here.</li></ul><p>The volume mount is worth a closer look, because it’s the part that makes runtime config possible. We mount the ConfigMap as a volume and use subPath to drop just the env.json file into nginx’s web root (/usr/share/nginx/html/env.json), replacing the one that was baked into the image at build time. So the env.json that nginx serves now comes from the ConfigMap, not from inside the image. (You can read more about using ConfigMaps as volumes <a href="https://kubernetes.io/docs/concepts/configuration/configmap/">here</a>.)</p><p>As I mentioned at the start, this is where I hit the issue: “Kubernetes refusing to use that local image and trying to pull it from Docker Hub instead.” That happened because I hadn’t added this line to the container spec:</p><pre>imagePullPolicy: IfNotPresent</pre><p>Here’s what’s going on. Because our image is tagged :latest, Kubernetes defaults its pull policy to Always — which means it ignores the local image we just loaded into Minikube and tries to pull it from Docker Hub instead. Since the image only exists locally, the pull fails and the pod lands in ImagePullBackOff. Setting imagePullPolicy: IfNotPresent tells Kubernetes “use the local copy if it’s already there,” which is exactly what minikube image load gave us.</p><p>The final deployment file now looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WXmtI5lkVbsyNx1-rCL5dQ.png" /></figure><p>Now that the deployment file is ready, we have to create the ConfigMap we’re referencing as a volume first, before we apply the deployment — otherwise Kubernetes will complain that the ConfigMap doesn’t exist.</p><pre>vi configmap.yaml</pre><p>Paste this content into the file:</p><pre>apiVersion: v1<br>data:<br>  env.json: |<br>    {<br>      &quot;apiUrl&quot;: &quot;https://www.productionurl.com&quot;,<br>      &quot;environment&quot;: &quot;prod&quot;<br>    }<br>kind: ConfigMap<br>metadata:<br>  creationTimestamp: null<br>  name: env-demo-config</pre><p><em>The ConfigMap holds the production JSON content, and when it’s mounted into a pod, Kubernetes generates a file named env.json with that content.</em></p><p>Now save it and create the ConfigMap:</p><pre>k apply -f configmap.yaml -n env-demo </pre><p>With the ConfigMap in place, we can apply the deployment:</p><pre>k apply -f dev.yaml -n env-demo</pre><p>We can check our pods with:</p><pre>k get pods -n env-demo</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*QehNgQGL2qWprc0zcup8XQ.png" /></figure><p>Finally, let’s create the service to expose our deployment:</p><pre>vi service.yaml</pre><p>Paste this content:</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  creationTimestamp: null<br>  labels:<br>    app: env-demo-svc<br>  name: env-demo-svc<br>spec:<br>  ports:<br>    - port: 80<br>      protocol: TCP<br>      targetPort: 80<br>  selector:<br>    app: env-demo<br>  type: NodePort<br>status:<br>  loadBalancer: {}</pre><p><em>The service is of type NodePort and targets our deployment using the selector app: env-demo.</em></p><p>Apply the service:</p><pre>k apply -f service.yaml -n env-demo</pre><p>After creating it, check that everything is running:</p><pre>kubectl get pods,svc,configmap -n env-demo</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*O4h0zKtHWnRpyzM_8p7LQA.png" /></figure><p>Now we can start the app:</p><pre>minikube service env-demo-svc -n env-demo</pre><p>When it’s successful, you should see a screen similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QyF4xIEzKy00BUL0sCMflQ.png" /></figure><p>And there it is — our prod config showing in a live app, served from the ConfigMap.</p><p>Now for the payoff. Let’s change a config value, and this time we don’t need to rebuild the Docker image at all — you just let your support team change the value in the ConfigMap and roll out the deployment.</p><p>Let’s change “environment”: “prod” to “environment”: “prod updated”.</p><p>You can use this command:</p><pre>k edit configmaps -n env-demo env-demo-config</pre><p>Change prod to prod updated for the environment value, then save the file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P3B1TaNSJOh6j67zBFVtBg.png" /></figure><p>Now reload the app in the browser… and nothing changed. That’s expected. The ConfigMap was updated, but the running pod is still serving the file it mounted when it started. We need to restart the deployment so it picks up the new ConfigMap contents:</p><pre>kubectl rollout restart deployment env-demo -n env-demo</pre><p>You can watch the rollout with:</p><pre>kubectl rollout status deployment env-demo -n env-demo</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*dM_EP3PBF1ubeRKiRdzq8Q.png" /></figure><p>Now go back and reload the app in the browser — you should see the updated value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p1RwPOVr6UEkRZTTtobWiQ.png" /></figure><p>Let’s quickly recap the whole journey. In Part 1 we built the Angular side — env files in the public directory, a runtime config service that loads them on startup, registered with provideAppInitializer so the values are ready before anything renders, then packaged it all into a small production Docker image. In Part 2 we took that same image to Kubernetes on Minikube, served env.json from a ConfigMap instead of from inside the image, and finally changed a config value on a running app without touching the image at all.</p><p>And along the way we hit the four gotchas that tripped me up — the ones the tutorials tend to skip:</p><p>1. Minikube can’t see your locally built image until you run minikube image load.</p><p>2. A :latest tag defaults to imagePullPolicy: Always, so Kubernetes ignores your loaded image and tries to pull from Docker Hub — set imagePullPolicy: IfNotPresent to use the local copy.</p><p>3. The ConfigMap has to exist before the Deployment that mounts it, or the apply complains.</p><p>4. Editing the ConfigMap changes nothing until you rollout restart — because we mounted the file with subPath, and subPath mounts don’t update live.</p><p>That last point is the real takeaway for me: the same subPath that lets us cleanly drop a single env.json next to index.html is also why the change needs a restart. It’s a trade-off, not a bug.</p><p>So that’s it. Your support team can now change configuration on a running Angular app the same way they already do for everything else — edit a ConfigMap, roll it out, done. No more rebuilding an image just to flip a URL.</p><p>Thanks for following along. If you found this useful, or you’re solving the same problem a different way, I’d love to hear about it in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97d95091d3a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Runtime Config for Angular on Kubernetes — No More Rebuilds]]></title>
            <link>https://medium.com/@kwamePrince/runtime-config-for-angular-on-kubernetes-no-more-rebuilds-23d72720fe9e?source=rss-4c912de4952f------2</link>
            <guid isPermaLink="false">https://medium.com/p/23d72720fe9e</guid>
            <dc:creator><![CDATA[Prince Acquah Darko]]></dc:creator>
            <pubDate>Fri, 24 Jul 2026 21:36:26 GMT</pubDate>
            <atom:updated>2026-07-24T21:40:09.214Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Runtime Config for Angular on Kubernetes — No More Rebuilds</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*1RGWrbkRp8k1-Ad_Doe99A.jpeg" /></figure><p>When I first started working with Kubernetes, whenever we needed to change a configuration value in our springboot apps, we’d just update a ConfigMap or a Secret, restart the pod, and we were done. No rebuilds, no new images, no waiting around.</p><p><em>But our Angular apps were a different story. Every time a config value had to change — an API URL, a feature flag, an environment label — we’d rebuild the image, re-tag it, and hand it off to the support team to redeploy. For something as small as flipping a single value, that always felt like too much.</em></p><p>So I went looking for a better way: what if an Angular app could read its configuration at runtime, the same way our Spring Boot apps do? Turns out it can — and in this two-part series I’ll show you exactly how I did it.</p><p>In Part 1, we’ll build it from the ground up: set up environment files, load them at runtime with an initializer-based config service, wire the values into the app, and package the whole thing into a Docker image. In Part 2, we’ll take that image to Kubernetes and prove the payoff — changing config in a live app without ever rebuilding it.</p><blockquote>A quick heads-up before we start: this series assumes you’re already comfortable with the basics of Angular and Kubernetes — specifically Pods, Services, and ConfigMaps. I won’t be explaining those from scratch. If any of them are new to you, don’t worry — just keep a tab open to look them up as we go, and you’ll be fine.</blockquote><p>Now let’s get started.</p><p>First, let’s generate a new Angular app for this demo. I created one in Angular 20 named env-demo using the command ng new env-demo.</p><p>This should generate the project structure, resulting in something like this below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*D4MJflqjG3sn2gg6UQYF0g.png" /></figure><p>Now let’s begin by creating our env files. Inside the public directory, create two new files, env.json and env.prod.json.</p><p>The env.json should have the following content:</p><pre>{<br>  &quot;apiUrl&quot;: &quot;http://localhost:3000&quot;,<br>  &quot;environment&quot;: &quot;local-dev&quot;<br>}</pre><p>the env.prod.json should have this</p><pre>{<br>  &quot;apiUrl&quot;: &quot;https://www.example.com/api&quot;,<br>  &quot;environment&quot;: &quot;production&quot;<br>}</pre><p>Next, in the app directory inside the src folder, let’s create a service that will be called when the app initializes. Let’s name it runtime-config.ts.</p><p>The file should have this content:</p><pre>import { HttpClient } from &#39;@angular/common/http&#39;;<br>import { inject, Injectable, signal } from &#39;@angular/core&#39;;<br>import { firstValueFrom } from &#39;rxjs&#39;;<br>import { configData } from &#39;./models&#39;;<br><br>const FALLBACK: configData = {<br>  apiUrl: &#39;http://unknown:3000&#39;,<br>  environment: &#39;unknown&#39;,<br>};<br><br>@Injectable({<br>  providedIn: &#39;root&#39;,<br>})<br>export class RuntimeConfig {<br>  private readonly http = inject(HttpClient);<br><br>  private readonly _config = signal&lt;configData&gt;(FALLBACK);<br>  readonly config = this._config.asReadonly();<br><br>  async load(): Promise&lt;void&gt; {<br>    const url = `env.json?ts=${Date.now()}`;<br>    try {<br>      const cfg = await firstValueFrom(this.http.get&lt;configData&gt;(url));<br>      this._config.set(cfg);<br>    } catch {<br>      this._config.set(FALLBACK);<br>    }<br>  }<br>}</pre><p>In this file we have a service that injects the HttpClient, which we use to make a call to fetch our configuration (our env values), which we then save in a signal called config.</p><p>In the load method, we make a call to env.json?ts={Date.now()}. Since it’s HttpClient, it returns an observable, which we then convert to a promise using firstValueFrom.</p><p>Now, where do we get the URL we’re making the call to? When we finally build our Angular app, the contents of our public directory are brought to the root directory, based on the configuration in our angular.json file:</p><pre>&quot;assets&quot;: [<br>    {<br>      &quot;glob&quot;: &quot;**/*&quot;,<br>      &quot;input&quot;: &quot;public&quot;<br>    }<br>  ],</pre><p>Hence we can make a call to env.json, which will then return a response. The date timestamp you’re seeing is to help us deal with stale cache issues. When there’s an error, we return the fallback to prevent the app from hanging.</p><p>Next let’s register this service so it fires when the app starts.</p><p>Inside the app.config.ts file, in the providers array, add the provideAppInitializer provider and inject the RuntimeConfig, as shown below:</p><pre>export const appConfig: ApplicationConfig = {<br>  providers: [<br>    provideBrowserGlobalErrorListeners(),<br>    provideZonelessChangeDetection(),<br>    provideHttpClient(),<br>    provideRouter(routes),<br>    provideAppInitializer(() =&gt; inject(RuntimeConfig).load()),<br>  ]<br>};</pre><p>Next, in our app component file, we can start using these config values.</p><p>In our app.ts file, let’s inject the service and make the values accessible. Include the following content in the app.ts file:</p><pre>export class App {<br>  protected readonly title = signal(&#39;env-demo&#39;);<br><br>  private readonly runtime = inject(RuntimeConfig);<br><br>  protected readonly config = this.runtime.config;<br>}</pre><p>And in its corresponding HTML file, where we just display the values to the screen:</p><pre>&lt;div&gt;<br>  &lt;h1&gt;ENVIRONMENT: {{ config().environment }}&lt;/h1&gt;<br>  &lt;p&gt;API URL: {{ config().apiUrl }}&lt;/p&gt;<br>&lt;/div&gt;</pre><p>We’re done with Angular for now. You can start your app, and you should see this on your screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mTctirqnRElBpsZLArvAJA.png" /></figure><p>Now we need to build our Angular app, generate an image, and deploy it on a Kubernetes environment.</p><p>Let’s proceed by creating a Dockerfile at the root directory with the following content:</p><pre># --- Stage 1: build ---<br>FROM node:22-alpine AS build<br>WORKDIR /app<br><br>COPY package.json package-lock.json ./<br>RUN npm ci<br><br>COPY . .<br>RUN npm run build -- --configuration production<br><br># --- Stage 2: serve ---<br>FROM nginx:1.27-alpine<br>COPY nginx.conf /etc/nginx/conf.d/default.conf<br>COPY --from=build /app/dist/env-demo/browser /usr/share/nginx/html<br><br>EXPOSE 80<br>CMD [&quot;nginx&quot;, &quot;-g&quot;, &quot;daemon off;&quot;]</pre><p>this is a multi-stage build, which keeps our final image small. in stage 1 we use a node image to install our dependencies (npm ci installs them exactly as locked in package-lock.json) and produce a production build of the angular app. in stage 2 we throw all of that away and start fresh from a lightweight nginx image, copying in only the built static files from stage 1 plus our nginx config. the result is an image that ships just the compiled app and a web server, no node, no source code, no node_modules.</p><p>now lets add our nginx file to serve our angular app</p><pre>server {<br>  listen 80;<br>  server_name _;<br>  root /usr/share/nginx/html;<br>  index index.html;<br><br>  # Runtime config file — mounted from a ConfigMap in k8s.<br>  # Must never be cached, otherwise config changes won&#39;t propagate.<br>  location = /env.json {<br>    add_header Cache-Control &quot;no-store, no-cache, must-revalidate&quot; always;<br>    expires -1;<br>    try_files $uri =404;<br>  }<br><br>  # SPA fallback: deep links resolve to index.html.<br>  location / {<br>    try_files $uri $uri/ /index.html;<br>  }<br>}</pre><p>this config does two important things. first, the dedicated location for /env.json sends no-cache headers so this file is never cached by the browser. this is the key to the whole approach, when we later change config in kubernetes we want the app to always fetch the latest values, not a stale copy. second, the location / block is the standard SPA fallback, it routes any unknown path back to index.html so angular’s router can handle deep links and page refreshes instead of nginx returning a 404.</p><p>now we are done lets build our angular app, run this command assuming you have docker installed.</p><pre>  docker build -t env-demo .</pre><p>when it successfully builds. you can then run your app using the command</p><pre>docker run -p 8080:80 env-demo</pre><p>you can then visit the app on <a href="http://localhost:8080/">http://localhost:8080</a> to view your docker app.</p><p>Wrapping up Part 1</p><p>And that’s it for Part 1. Let’s quickly recap what we did. We set up our environment files in the public directory, built a runtime config service that loads them on app initialization, registered it with provideAppInitializer so the values are ready before anything renders, and displayed those values in our component. Then we packaged the whole thing into a small, production-ready Docker image and ran it locally.</p><p>But notice that nothing magical has happened yet — so far our config is still baked into the image at build time. If we wanted to change a value right now, we’d be back to rebuilding the image, which is exactly the problem we set out to solve.</p><p>That’s where Part 2 comes in. We’ll take this same image to Kubernetes (running on Minikube), serve env.json from a ConfigMap instead of from inside the image, and finally see the payoff — changing a config value in a live app without rebuilding or re-shipping anything. We’ll also walk through a couple of gotchas that tripped me up along the way, like why Kubernetes ignores your locally loaded image and how to actually make a config change show up.</p><p>See you in Part 2 <a href="https://medium.com/@kwamePrince/runtime-config-for-angular-on-kubernetes-no-more-rebuilds-part-2-97d95091d3a8">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23d72720fe9e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Retrieving Route Parameters in Angular]]></title>
            <link>https://medium.com/@kwamePrince/retrieving-route-parameters-in-angular-aa0d1d4e1bc8?source=rss-4c912de4952f------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa0d1d4e1bc8</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Prince Acquah Darko]]></dc:creator>
            <pubDate>Wed, 22 Nov 2023 13:21:10 GMT</pubDate>
            <atom:updated>2023-11-22T13:29:06.443Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*nbJ41jD1-r2Oe6FsLjKaOg.png" /></figure><p>Often, when users navigate through our app, we would like to retrieve route parameters and display data on the page based on these parameters. This guide will help you learn how to retrieve route parameters in Angular, using the Input feature released in Angular 16, by building a simple books app.</p><h4><strong>First Things First</strong></h4><p>Let’s begin by creating a new Angular app from the terminal using the following command: ng new booksApp — defaults</p><blockquote>This command creates a new Angular project named ‘booksApp’ and selects default options for all prompts during the project creation process.</blockquote><p>Now, change directory into our newly created project ‘booksApp’ and create two new components using the commands ng g c author &amp;&amp; ng g c book</p><p>Here, we generate two new components using the ng generate component command (shortened to ng g c). The &#39;author&#39; component will display the list of authors, while the &#39;book&#39; component will display the list of books by various authors.&quot;</p><p><strong>Setting Up Routes</strong></p><p>Let’s configure routes for our ‘booksApp’ by opening the ‘app.routes.ts’ file and pasting the following content:</p><pre>import { Routes } from &#39;@angular/router&#39;;<br>import { AuthorComponent } from &#39;./author/author.component&#39;;<br>import { BooksComponent } from &#39;./books/books.component&#39;;<br><br>export const routes: Routes = [<br>  {<br>    path: &#39;author&#39;,<br>    component: AuthorComponent,<br>  },<br>  {<br>    path: &#39;books/:authorId&#39;,<br>    component: BooksComponent,<br>  },<br><br>  {<br>    path: &#39;&#39;,<br>    redirectTo: &#39;author&#39;,<br>    pathMatch: &#39;full&#39;,<br>  },<br>];</pre><p>In the code above, we’ve set up three routes:</p><ol><li>The first route object in the routes array essentially means that when a user visits the ‘author’ page (e.g., <a href="http://www.website.com/author">www.website.com/author</a>), the Author component will be displayed.</li><li>The second route is somewhat similar to the first one but takes in a route parameter, acting as a placeholder for the author’s ID. It loads the ‘books’ component containing books by the author whose ID corresponds to the placeholder. The placeholder will be accessed using the Input feature.</li><li>The third configuration simply indicates that when someone visits the root URL of your application, they will be redirected to the ‘author’ page.</li></ol><p><strong>Displaying a List of Authors</strong></p><p>Open the ‘author.component.ts’ file and create a property named ‘authors’ in the class with the following content:</p><pre>export class AuthorComponent {<br>  authors = [<br>    {<br>      id: 1,<br>      name: &#39;James&#39;,<br>    },<br>    {<br>      id: 2,<br>      name: &#39;John&#39;,<br>    },<br>    {<br>      id: 3,<br>      name: &#39;Abigail&#39;,<br>    },<br>  ];<br>}</pre><p>Replace the markup in the ‘author.component.html’ file to loop over the elements in the ‘authors’ array and display their names as shown below:</p><pre>&lt;ul&gt;<br>  @for (author of authors; track author.id) {<br>  &lt;li&gt;<br>    &lt;a&gt;{{ author.name }}&lt;/a&gt;<br>  &lt;/li&gt;<br>  }<br>&lt;/ul&gt;</pre><blockquote>Here, we loop through each item in the array using the new built-in control flow released in Angular 17. We also track by the author’s ID; you can track by the entire author object or by $index if you prefer. Tracking helps Angular associate array items with the views in the DOM, allowing it to perform a minimal set of DOM operations as items are added, removed, or moved in a collection.</blockquote><p>Let’s now view our app in the browser. But before that, let’s open the ‘app.component.html’ file and replace the content with &lt;router-outlet/&gt;. This is where the routes we set in the &#39;app.routes.ts&#39; file are going to be displayed.</p><blockquote>The &lt;router-outlet/&gt; directive has already been imported by Angular in the imports array of the &#39;app.component.ts&#39; file, so we can go ahead and use it. While you&#39;re there, you can also remove the import of CommonModule since we won&#39;t be needing it. This step also aids in tree shaking</blockquote><p>Run ng serve -o in the root directory of our app to open it in a browser. If everything works well, you should see a list of author names displayed in the browser.</p><p><strong>Displaying a List of Books Associated with Authors</strong></p><p>To display a list of books associated with an author when a user clicks on an author, let’s modify the ‘author.component.html’ file as shown below</p><pre>&lt;ul&gt;<br>  @for (author of authors; track author.id) {<br>  &lt;li&gt;<br>    &lt;a [routerLink]=&quot;&#39;/books/&#39; + author.id&quot;&gt;{{ author.name }}&lt;/a&gt;<br>  &lt;/li&gt;<br>  }<br>&lt;/ul&gt;</pre><p>The routerLink is a directive that helps us navigate to the &#39;books/:authorId&#39; page when a user clicks on an author. To use routerLink, we need to import it into our TypeScript class where this HTML file is registered. Open the &#39;author.component.ts&#39; file, import the RouterLink directive, and add it to the imports array.</p><pre>import { RouterLink } from &#39;@angular/router&#39;; &lt;&lt;----<br><br>@Component({<br>  selector: &#39;app-author&#39;,<br>  standalone: true,<br>  imports: [RouterLink], &lt;&lt;---- <br>  templateUrl: &#39;./author.component.html&#39;,<br>  styleUrl: &#39;./author.component.css&#39;,<br>})</pre><p>We have completed the author component. Let’s now shift our focus to the books component to display the list of books associated with authors.</p><p>In the ‘books.component.ts’ file, add a ‘books’ property to the class, which contains the titles of books written by various authors. Additionally, include an @Input where the name corresponds to the route parameter set up in the &#39;app.routes.ts&#39; file. This Input helps us retrieve the route parameters. Ensure to import Input from &#39;@angular/core&#39;.</p><pre>import { Component, Input } from &#39;@angular/core&#39;;<br><br>export class BooksComponent {<br>  books = [<br>    {<br>      id: 1, authorId: 1, title: &#39;The Color of Magic&#39;<br>    },<br>    {<br>      id: 2, authorId: 1, title: &#39;The Light Fantastic&#39;<br>    },<br>    {<br>      id: 3, authorId: 2, title: &#39;The Name of the Wind&#39;<br>    },<br>    {<br>      id: 4, authorId: 2, title: &#39;The Wise Man\&#39;s Fear&#39;<br>    },<br>    {<br>      id: 5, authorId: 3, title: &#39;The Hunger Games&#39;<br>    },<br>    {<br>      id: 6, authorId: 3, title: &#39;Catching Fire&#39;<br>    },<br>    {<br>      id: 7, authorId: 3, title: &#39;Mockingjay&#39;<br>    }<br>  ]<br>  @Input() authorId!: string;<br><br>}</pre><p>Whenever we receive an authorId, we would like to filter the books array to include only those whose authorId corresponds to the authorId that was passed in. To start with that, let&#39;s create another property named authorsBooks and set it to an empty array. Then, let&#39;s convert the @Input to a setter. In the setter, we&#39;ll filter the books array to include only those whose authorId corresponds to the authorId that was passed in and save the results to the authorsBooks property we created.</p><pre><br>  authorsBooks: {id:number, authorId:number, title:string}[] = [];<br><br>  @Input() <br>  set authorId(id: string) {<br>    this.authorsBooks = this.books.filter(i =&gt; i.authorId === +id)<br>  }</pre><p>To display our filtered results in the template, open the ‘books.component.html’ file and update the markup as follows:</p><pre><br>&lt;ul&gt;<br>  @for (book of authorsBooks; track book.id) {<br>  &lt;li&gt;<br>    &lt;a&gt;{{ book.title }}&lt;/a&gt;<br>  &lt;/li&gt;<br>  }@empty {<br>    &lt;span&gt; No books found&lt;/span&gt;<br>  }<br>&lt;/ul&gt;</pre><blockquote>We loop through the ‘authorsBooks’ array and display their titles. If there are no books, we display ‘No books found’.</blockquote><p>Finally, to use the Input feature, we need to register it in our ‘app.config.ts’ file by importing ‘withComponentInputBinding’ and adding it as an argument to the ‘provideRouter’.</p><pre>//app.config.ts<br><br>import { ApplicationConfig } from &#39;@angular/core&#39;;<br>import { provideRouter, withComponentInputBinding &lt;&lt;&lt;-here} from &#39;@angular/router&#39;;<br><br>import { routes } from &#39;./app.routes&#39;;<br><br>export const appConfig: ApplicationConfig = {<br>  providers: [provideRouter(routes, withComponentInputBinding() &lt;&lt;&lt;-here)]<br>};</pre><p>Now, let’s view our app in the browser, and it should function as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*ETVIcuTG058ZWbHL0w3REg.gif" /></figure><p>Great job! We’ve successfully accessed the route parameter and displayed books by authors based on the route parameter using the Input feature. Keep in mind that this Input feature is not limited to just route parameters (e.g., books/:authorId); it can also be utilized for accessing query parameters (e.g., books?authorId=…) in the same way.</p><p>Feel free to give it a try, and don’t hesitate to reach out to me on <a href="https://medium.com/@kwamePrince">Medium </a>or <a href="https://twitter.com/kwamePrince_">Twitter</a> if you have any questions.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa0d1d4e1bc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>