Retrieve parent route parameters from a dynamically loaded route component

Struggling to access the parent route params in a lazy loaded route component using activatedRoute.parent.params. Despite this not working, I have managed to find a solution that involves fetching the value using an array index number which feels like a 'magic' workaround.

Is there a more elegant method available that doesn't require retrieving the value through an array (

this.activatedRoute.pathFromRoot[1]
)?


The route setup for lazy loading a module looks like this:

parent.route

routes:Routes = [
    {
        path: "dashboard/:id",
        component: dashboard.DashboardComponent,
        canActivate: [guard.LoggedInGuard],
        children: [
            {
                path: "my-dock",
                loadChildren: 'path/child.module#Child'
            }
        ]
    }
];

In the default component for child.module, the code is as follows:

child.component

ngOnInit() {
    this.activatedRoute.pathFromRoot[1].params.subscribe((params: Params) => {
        console.log(params); // returns {id: "123456789"}
    });

    this.activatedRoute.parent.params.subscribe((params: Params) => {
        console.log(params);  // returns {}
    });
}

Wondering why

this.activatedRoute.parent.params
does not work to retrieve the id param?

Answer №1

One interesting feature is accessing data from the parent of the parent router. While it may seem odd in certain project setups, being familiar with your router structure allows you to accomplish this.

 constructor(
    private route: ActivatedRoute

)
this.route.parent.parent.params.subscribe( (params) => {
        console.log(params);
        this.urlKey = params['urlKey'];
    });

Answer №2

I have found that the following techniques are functioning flawlessly within Angular-6 (potentially also in Angular-5, although not confirmed)

// approach 1
this.activatedRoute.pathFromRoot[1].params.subscribe((parms: Parms) => {
    console.log(parms);
});

// approach 2    
this.activatedRoute.parent.params.subscribe((parms: Parms) => {
    console.log(parms);
});

Q. What is the reason I am unable to utilize this.activatedRoute.parent.params to access the id parameter?

A. It appears that you did not specify the version of Angular being used, but as per my experience with Angular-6, both of these approaches should function effectively.

Answer №3

To avoid relying on the 'magic' array index number, one efficient solution is to utilize a Service.

  • Retrieve the Parameters or URL within the parent component and store them in a service.
  • Access these parameters from the service variable within the Lazy loaded component. Something along these lines:

ParentComponent

constructor(private router : Router){
    this.service.setParams(this.router.url);//you may need to parse here
    //Alternatively, you can use ActivatedRoute and subscribe to params
}

Service

params:string;

setParams(params:string){
    this.params = params;
}

getParams(){
    return this.params;
}

Now, within the child Lazyloaded component, you can access the parameters using service.getParams()

Answer №4

Dealing with a similar problem, I tested out the following solution:

this.router.parent.parent 

This method proved to be very effective for me.

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

Custom Error Page Implementation in Angular and Spring Boot

I keep running into a Whitelabel Error Page (error 404) whenever I attempt to access any page on my Angular 9 application, except for the root route. Interestingly, using the page buttons within the Angular router functions perfectly fine. Despite trying ...

Guide to sending a HTTP POST request with parameters in typescript

I need assistance sending a POST request using parameters in the following format: http://127.0.0.1:9000/api?command={"command":"value","params":{"key":"value","key":"value","key":"value","key":value,}} I attempted to do this but encountered an issue: l ...

Using Angular 2 to select with default value from a separate model

Is there a way to set the default value or link to another model while utilizing NgFor on a different model? The model intended for binding is as follows: "Bookings": {"dates": [{"date":"3-10-2016","slot":"Full"}, {"date":"4-10-2016","slot":"Full"}, {"da ...

How to target a particular Textfield in React with its unique identifier

I'm working on a component that contains various Textfields and need to access specific IDs. For example, I want to target the textfield with the label 'Elevator amount'. I attempted the following code snippet but am unsure of how to correct ...

Encountering issues with Proxy functionality in the latest versions of Angular 13 and Spring Boot

I've encountered an issue with the proxy configuration in Angular. I'm unsure if it's a problem within my Angular settings or if there's a configuration issue in Spring. For testing purposes, I have a backend built in springboot to han ...

Error encountered while attempting to load an image in a React component using TypeScript linting

I am currently working on a React app with Next.js where I have imported an image using the following code: import image1 from '../../../img/dummy-image-2.jpg'; Subsequently, I use the image in my app like so: <img src={image1} alt="Dumm ...

Get rid of the Modal simply by clicking on the X mark

Objective: The modal should only be closed by clicking the X mark and not by clicking outside of it. Challenge: I am unsure how to resolve this issue when using the syntax code [config]="{backdrop: 'static'}" Additional Information: I am new ...

You are not able to use *ngIf nested within *ngFor in Angular 2

I am currently working in Angular2 and trying to bind data from a service. The issue I am facing is that when loading the data, I need to filter it by an ID. Here is what I am trying to achieve: <md-radio-button *ngFor="#item of items_list" ...

Steps for excluding a file from compilation during angular testingExclude a file from being

I have a dilemma with my Angular 7 application that I built using the angular cli. During the ng-test process, I need a specific file to be excluded from compilation. The file causing issues is "app/config/context.prod.ts" To rectify this, I included th ...

Is it possible to open a PDF file in a new tab using Angular 4?

When attempting to open a PDF file using the window.open() function, I encountered an issue where the window would open and close automatically, causing the file to be downloaded rather than displayed in a new tab. Despite not having any ad blockers inst ...

Establish a connection between a variable and the selected value of Mat-select using a form

Within my TypeScript code, there exists a variable named type whose value is provided by its parent component. This type value is essentially a string that has the possibility of being empty upon being received from the parent component. Additionally, in t ...

In Node.js, retrieve all users from the database and display only the users' name, id, and image, excluding

I'm trying to fetch the names, profile pictures, and IDs of all users using the User.find() method. However, this method is returning all data including sensitive information like passwords and addresses. My goal is to only retrieve the name, ID, and ...

Is there a way for me to retrieve the complete error response using the catchError method?

I'm currently testing my UI's response to a 404 message by deliberately triggering it in my application. For my backend API, I am utilizing NestJs. One of my methods for retrieving an organization is structured as follows: async findOne(organiza ...

The protractor-jasmine2-screenshot-reporter seems to be failing to generate the necessary screenshots within the designated folder

I have encountered an issue with my protractor.conf.js file and need some assistance. I have created the target/screenshots folder manually in the root of my angular-cli project, but when I run protractor conf.js, the protractor tests in the browser window ...

Obtain the selected portion of text value using Angular 2

In order to create a basic text editor that allows users to make selected text bold, follow these steps: Start by setting up a textarea with the value "Super text". Next, select a portion of this text (such as "Super"). But how can you retrieve the selec ...

Creating a personalized design for MUI TextField spin button

Looking to customize the appearance of the up/down spin buttons in MUI TextField. Desiring white arrows and a black surrounding area that's slightly larger, akin to this: I'm aware that adjustments need to be made within input::-webkit-outer-sp ...

One or multiple web browsers set in the Browserslist of the project

I have recently started working with the Ionic framework and encountered some warnings while setting up my application. Can anyone help me with a solution? [ng] When starting the Ionic application, I received the following warnings: [ng] One or more browse ...

Guide on how to upload files to a web server using Angular frontend only

My website's frontend is built with Angular and it allows users to upload files. I am looking for a way to store these uploaded files on the web server where my website is currently hosted. Ideally, I would like to accomplish this using just Angular, ...

When we mention TypeScript and CDK, we are actually talking about the very foundation

As I was working on my current Stack constructor, I came across the Stack.formatArn() method. I started to wonder about the difference between using this.formatArn() and cdk.Stack.of(this).formatArn(). After all, shouldn't "this" refer to the stack it ...

Defining the range of an array of numbers in TypeScript: A complete guide

When working with Next.js, I created a function component where I utilized the useState hook to declare a variable for storing an array of digits. Here is an example: const [digits, setDigits] = useState<number[]>(); I desire to define the range of ...