Observe the parameters of the first child by subscribing to ActivatedRoute

Looking for input on a better approach to implement this feature. If you have any suggestions, feel free to share them.

I am working on creating a system with multiple inboxes where users can group their emails in different categories.

For instance, http://localhost/inbox/personal/ will display emails in the personal inbox, while

http://localhost/inbox/business/3
will show emails in the business inbox and highlight the email with the ID: 3

The routes are structured like this:

const routes: Routes = [
  {
    path: '',
    pathMatch: 'full',
    redirectTo: 'personal' // redirect to personal inbox
  },
  {
    path: ':inbox',
    component: InboxContentComponent, // list of emails in :inbox
    children: [
      {
        path: '',
        component: InboxNoSelectedEmailComponent, // no email selected
      },
      {
        path: ':id',
        component: InboxSelectedEmailComponent, // show selected email content
      }
    ]
  }
];

I am having difficulty with the InboxContentComponent as I need to track changes in the inbox and whether an email is selected or not.

  constructor(private route: ActivatedRoute) {
  }
  ngOnInit() {
    this.route.paramMap.subscribe(inbox => {
      console.log('inbox', inbox);
    });
  }

Currently, events are only triggered when the inbox changes and not when the email changes. Is there a way to detect changes in the child route parameters?

Using

this.route.firstChild.paramMap.subscribe();
only works if the route has a first child during initialization. If the route is http://localhost/inbox/business/, then this.route.firstChild is null

One solution I considered is defining routes like this:

{
    path: ':inbox/:id',
    component: InboxContentComponent
}

and then checking in the InboxContentComponent if :id is set or not.

Any thoughts on this approach?

Answer №1

In order to address this type of issue, my approach would involve monitoring router events and extracting the necessary information. Here is an example of how this could be achieved:

import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
import { filter, map, mergeMap, tap } from 'rxjs/operators';

// ...
constructor(
    // ...
    private activatedRoute: ActivatedRoute,
    private router: Router
  ) {
    this.router.events
    .pipe(
      filter((event) => event instanceof NavigationEnd),
      map(() => this.activatedRoute),
      map((route) => {
        while (route.firstChild) route = route.firstChild;
        return route;
      }),
      mergeMap((route) => route.paramMap),
      tap(
        paramMap => console.log('ParamMap', paramMap)
      )
    ).subscribe(
      (paramAsMap) => // Extract the parameters (paramAsMap.params) and utilize them for highlighting or any other specific task
    )
  }

This code snippet can be customized according to your requirements. Depending on the parameters, you can choose to highlight or not to highlight.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How come this constant can be accessed before it has even been declared?

I find it fascinating that I can use this constant even before declaring it. The code below is functioning perfectly: import { relations } from 'drizzle-orm' import { index, integer, pgTable, serial, uniqueIndex, varchar } from 'drizzle-orm ...

Angular's Reactive forms: The power of bidirectional binding

Struggling with Reactive forms? I've encountered an issue where updating the model class when a User changes the input is easy, but what about programmatically changing the model and reflecting those changes in the HTML form? In simplified terms: th ...

There is a WARNING occurring at line 493 in the file coreui-angular.js located in the node_modules folder. The warning states that the export 'ɵɵdefineInjectable' was not found in the '@angular/core' module

I encountered a warning message while running the ng serve command, causing the web page to display nothing. Our project utilizes the Core Ui Pro Admin Template. Here is the list of warning messages: WARNING in ./node_modules/@coreui/angular/fesm5/coreu ...

angular2 Formatting Dates in Material 2 Datepicker

I'm currently utilizing the Angular Material datepicker in my angular4 project. I am looking for a way to format the selected date in the input box with a shorter format such as "May 29, 2017" instead of the current display which is "29/05/2017". Can ...

I am experiencing an issue with my date filter where it does not display any results when I choose the same date for the start and end dates. Can anyone help me troub

Having an issue with my custom filter pipe in Angular. When I select the same dates in the start and end date, it doesn't display the result even though the record exists for that date. I've noticed that I have to enter a date 1 day before or ea ...

Setting up Firebase in an NX Workspace

Looking for a way to set up an Nx Workspace with Firebase that can deploy multiple applications within the monorepo. Ideal file structure would resemble something like this: https://i.sstatic.net/oKJrT.png To deploy the various applications, hoping to pas ...

The validation process in reactive forms is experiencing some issues with efficiency

Trying to debug an issue with my reactive forms - the repeatPassword field doesn't update as expected. When entering information in the "password" field, then the "repeatPassword" field, and back to "password", the second entry is not flagged as inval ...

Using an image instead of a checkbox when it is selected (Angular 4/Ionic 3)

Is there a way to swap out the checkbox for an image? I want this image to change dynamically based on whether the checkbox is checked or not. Unfortunately, adding a class doesn't seem to do the trick as it modifies all icons in the same column. The ...

Encountering a problem with package-lock.json during project deployment

My project publishing attempts keep resulting in the same error showing up repeatedly in the logs: Any thoughts on how this issue can be resolved? 18 error Command failed: git -c core.longpaths=true add D:...\main\backend\package-lock. ...

What is the reason behind Typescript executing the abstract class before anything else?

I'm currently facing a challenge solving an abstract class problem with Typescript. Let me explain what I am trying to accomplish. There is a class named Sword that extends Weapon. Each Weapon must have certain properties like the damage, but since e ...

Creating dynamic keys using Typescript and JSON data format

Currently, I am developing an application using Typescript and React Native. Within my app, I have a JSON file containing information about poker hands that needs to be accessed. The structure of the JSON data is as follows: { "22": [ [ ...

Mastering the Art of Handling Postgres Error Messages for Accurate Query Execution

Currently, I am utilizing pg and node.js. The issue arises when a user logs in through the auth0 widget, as I am passing the returned email to check against my database for existing users. If the user does not exist, I am inserting their information into t ...

Is it possible to verify type equality in Typescript?

If the types do not match, I want to receive an error. Here is an example of an object: const ACTIVITY_ATTRIBUTES = { onsite: { id: "applied", .... }, online: { id: "applied_online", .... }, ... } as co ...

collections of Angular2 rc scripts

I am currently in the process of migrating my app from version 0.17 to RC 0 and I have encountered some challenges. In version 0.17, we used the following scripts (bundles): <script src="node_modules/angular2/bundles/angular2-polyfills.js"></scri ...

Is there a way to add an event listener to dynamically generated HTML using the v-html directive?

I have a string variable named log.htmlContent that contains some HTML content. This variable is passed into a div to be displayed using v-html. The particular div will only be displayed if log.htmlContent includes an img tag (http: will only be present in ...

How can I adjust the indentation in Angular Prime-ng's p-tree component?

In my project, I am utilizing the primg-ng tree component for the sidebar. Currently, the output is displayed as shown here: https://i.stack.imgur.com/kcSQt.png However, I am looking to maintain consistent indentation levels without any adaptive changes ...

Trouble displaying object in template using Angular's ngrx

Within my Typescript interface, I have declared the following structure: export interface FolderList { ADMIN: [Folder[], string, string]; SUPERADMIN: [Folder[], string, string]; USER: [Folder[], string, string]; } The 'Folder' interface is de ...

Every time I attempt to execute an npm command, such as ng new, I encounter a "module not found" error despite having installed node version "v16.13.0"

https://i.stack.imgur.com/RBxyI.png node:internal/modules/cjs/loader:936 throw err; ^ Error: Cannot locate module 'C:\Program Files\nodejs\node_modules\npm\bin\node_modules\npm\bin\npm-cli.js' ...

Utilize ngFor within a ng-template to display dynamic content in a table structure

Currently, I am attempting to loop through a list that is obtained from an API request and then populate the data into a table. The issue I am facing is that this table exists within an ng-template tag, and I am unsure of how to manage this situation. Thi ...

Is there a way to apply a decorator to a function that has been returned?

Can the following be accomplished? bar () { @custom yield () => { } } ...