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

npm ERROR! Encountered an unexpected symbol < within the JSON data at position 12842

I keep encountering an error every time I attempt to install a package or run npm install. Despite my limited experience with Angular 4, having only started using it a week ago, I am puzzled by this error. Any guidance on how to resolve it would be greatly ...

Organizing Telephone Number Entries in Angular

In my search for a way to format a phone number input field in Angularjs, I have come across many solutions, but none specifically for Angular 7. What I am looking to achieve is for the user to enter the textfield like so: 123456789 and have the textfi ...

angular2 variable turns null during post request, synchronization breakdown

Currently, I am in the process of developing an ecommerce web application using Angular2 and have encountered a issue with saving ordered information in session. addToCart(productId:string,noOfItems:number):void{ let itemCounts; let selectedItems= ...

The error message "Angular 2 - Module not found: Error: Can't locate '@angular/material'" is indicating that the specified module or package is unable

I diligently followed every step outlined in the official guide: https://material.angular.io/guide/getting-started The Error I Encountered ERROR in ./src/app/app.module.ts Module not found: Error: Can't resolve '@angular/material' in ' ...

What steps are necessary to ensure that the extended attribute becomes mandatory?

Utilizing Express, I have set specific fields on the request object to leverage a TypeScript feature. To achieve this, I created a custom interface that extends Express's Request and includes the additional fields. These fields are initialized at the ...

Error in Angular FormArray: Unable to access the 'push' property because it is undefined

Currently, I am working with a form that is divided into 3 subcomponents, each containing 3 form groups. The 3rd group contains a FormArray which will store FormControls representing true/false values for each result retrieved from an API call. Initially, ...

The array containing numbers or undefined values cannot be assigned to an array containing only numbers

Currently facing an issue with TypeScript and types. I have an array of IDs obtained from checkboxes, which may also be empty. An example of values returned from the submit() function: const responseFromSubmit = { 1: { id: "1", value: "true" }, 2: ...

Leverage the power of Bootstrap 4 without incorporating its pre-built components

Is it possible to utilize Bootstrap 4 without its components? The diagram below seems to suggest otherwise, correct? My Scenarios: I need to implement Angular Material components instead of Bootstrap components. It's acceptable to use Bootstrap 4 ...

Execute a function using a click event within a statement

Is it possible to trigger a function with parameters based on the result of a statement? For example, can we achieve something like this: (click)="datavalue.elementDataCollection.length > 1 ? AddNewDialog (datavalue,datavalue.COCLabel,mainindex,i) : r ...

Show just a single error message if there are two validation errors present

In my AngularJS timepicker, users can choose multiple time segments for each day. The code has validation to detect duplicates and overlapping time segments. For example, entering 11:00am - 12:00am twice will trigger two error messages: 'Overlapping t ...

When utilizing Ionic components in Angular, you may encounter the error message "element not recognized."

I have recently developed an app using Ionic and Angular, but I am encountering a persistent error. Whether I place the HTML code in the default Ionic generated "pages" folder or in a custom page, the error persists. Ionic version 5.4.16 Angular version 1 ...

How to utilize FileReader for parsing a JSON document?

I'm currently facing an issue while attempting to read and copy a JSON file uploaded by the user into an array. When using .readAsText(), the returned data includes string formatting elements like \" and \n. Is there a way to utilize FileRe ...

Is it possible to create a click event for a mat-icon within a mat form field (either in the matprefix or matsuffix)?

I am working with a mat-form-field and have incorporated a custom mat-icon within it as a matprefix. However, I am now looking to create a click method for that matprefix icon. Despite my attempts to write a click method, it does not seem to be functioning ...

Angular: Incorporating a custom validation function into the controller - Techniques for accessing the 'this' keyword

I'm currently working on implementing a custom validator for a form in Angular. I've encountered an issue where I am unable to access the controller's this within the validator function. This is the validator function that's causing tr ...

`Browser Extension Compatibility``

I am currently working on developing a TypeScript extension that is compatible with all major browsers. I have come across the package https://www.npmjs.com/package/web-ext-types which I have integrated into my package.json file. While coding in TypeScrip ...

Mastering React children: A guide to correctly defining TypeScript types

I'm having trouble defining the children prop in TypeScript for a small React Component where the child is a function. class ClickOutside extends React.PureComponent<Props, {}> { render() { const { children } = this.props; return chi ...

Creating an Angular component that is flexible in terms of the data type it accepts

Currently, I have successfully implemented a lookup component that is responsible for fetching and filtering a list of users based on the query provided. When a user is selected from this list, they are set as members. This component can be configured with ...

Please click twice in order to log in to Angular 16

Whenever I attempt to log in, I face the issue of having to click twice. The first click does not work, but the second one does. Additionally, an error message pops up: TypeError: Cannot read properties of undefined (reading 'name'). I am unsure ...

displaying a pair of inputs next to each other

Is it possible to display two input fields side by side? I am using Angular's matInput forms, but struggling to position the second input next to the first. What I would like to achieve is to have "input1 , input2" on the same line. Here is my code: ...

Using ngModel to bind input fields with predefined default values

I have an input field and I'm trying to set default values, but when using ngModel the input fields are coming up empty. How can I set default values that the user can change? <div class="control"> <input #name="ngModel" ...