Creating dynamic routing functionality in Angular 8 allows for a more personalized and

I am struggling with setting up routing in Angular 8. Here is how I am trying to do it:

'company/:id/activity'
'company/:id/contacts'

However, I am not receiving any params in the activatedRoute:

this.activateRoute.params
            .subscribe(param => console.log(param) )

Any suggestions on how to resolve this issue?

Main Routing file:

{
                path: 'company/:id',
                children: [
                    {
                        path: '',
                        loadChildren: () => import('@app/features/company-view/company-view.module').then(m => m.CompanyViewModule)
                    }
                ]
            }

Lazy loaded routing file:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

import { CompanyViewComponent } from '@app/features/company-view/company-view.component';
import { PendingChangesGuard } from '@app/shared/guards';
import { CompanyActivityComponent } from './company-activity/company-activity.component';

const routes: Routes = [
  {
    path: '',
    component: CompanyViewComponent,
    children: [
      { 
        path: '', 
        redirectTo: 'view'
      },
      {
        path: 'activity',
        component: CompanyActivityComponent,
        data: {
          title: "Company Activity"
        }
      }
    ]
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class CompanyViewRoutingModule { }

If I use the following routing structure, everything works smoothly:

const routes: Routes = [
  {
    path: '',
    component: CompanyViewComponent,
    children: [
      {
        path: ':id/activity',
        component: CompanyActivityComponent,
        data: {
          title: "Company Activity"
        }
      },
      {
        path: '**',
        redirectTo: 'activity'
      }
    ]
  }
];

Now, I'm wondering how I can set the default routing to :id/activity ?

Answer №1

If you're looking to pass variables for your component through the routing process, it can be easily achieved. In your routes.ts file, simply specify the path like this: path: 'company/:id/:activity'. Once that's set up, you can retrieve these variables in your component.

The following code snippets demonstrate how to do so:

id = this.route.snapshot.params['id']
activity = this.route.snapshot.params['activity']

Once you have the variables, you can then pass them on to another component or utilize them as needed.

For example:

<app-testcomponent
    [id]="id"
    [activity]="activity">
</app-testcomponent>

Answer №2

I can't seem to find a proper route for the specified "view".

  { 
    path: '', 
    redirectTo: 'view'
  }

After some adjustments, I have updated it to "activity" and set it as the default catch-all route for that section of the tree. Additionally, I have made some changes to your routes. Please review both of them below:

Main Route

{
    path: 'company',
    children: [
        {
            path: '',
            loadChildren: () => import('@app/features/company-view/company-view.module').then(m => m.CompanyViewModule)
        }
    ]
}

Child Routes

const routes: Routes = [
  {
    path: ':id',
    component: CompanyViewComponent,
    children: [
      {
        path: 'activity',
        component: CompanyActivityComponent,
        data: {
          title: "Company Activity"
        }
      },
      { 
        path: '**', 
        redirectTo: 'activity'
      }
    ]
  }
];

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

Angular 9 Singleton Service Issue: Not Functioning as Expected

I have implemented a singleton service to manage shared data in my Angular application. The code for the service can be seen below: import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class DataS ...

Initiate a button click event from the parent element situated within an Iframe

I am facing a challenge in accessing a button within an iframe. The path to the button is as follows: div.iframe-container > iframe#builder-frame > html > body > div#header > ul.header-toolbar.hide > li > span.deploy-button-group.butt ...

Please replace the text with only letters and then submit it without any spaces, periods, commas, or other symbols

Whenever I encounter a form like this, I need to submit it and replace the text in the name field with only letters - no commas, spaces, or special characters. https://i.sstatic.net/9FQnT.png myform.html <script> function fixInput(event) { na ...

Meta tag information from Next.js not displaying properly on social media posts

After implementing meta tags using Next.js's built-in Head component, I encountered an issue where the meta tag details were not showing when sharing my link on Facebook. Below is the code snippet I used: I included the following meta tags in my inde ...

What is the best way to showcase the outcome on the current page?

This is a sample HTML code for a registration form: <html> <head></head> <body> <form id="myform" action="formdata.php" method="post"> username:<input type="text" name="username" id="name"><br> password:&l ...

Incorporate an image into a Component template by utilizing a URL that is provided as a property of the Component in Vue and Vite

One of the challenges I faced was setting the 'src' attribute of an image in a Component's template from a property value. Initially, I attempted to do this as follows: Gallery View, where the Component is called multiple times <script s ...

Is it possible to execute a REST call in JavaScript without utilizing JSON?

(I must confess, this question may show my lack of knowledge) I have a basic webpage that consists of a button and a label. My goal is to trigger a REST call to a different domain when the button is clicked (cross-domain, I am aware) and then display the ...

What is the best way to display or hide specific tables depending on the button chosen?

Being fairly new to JavaScript, I find myself unsure of my actions in this realm. I've successfully implemented functionality for three links that toggle visibility between different tables. However, my ideal scenario would involve clicking one link t ...

Eliminating any spaces in the password prior to finalizing the form submission

After submitting the Form, I am trying to remove all spaces from the Password field. This is my current code: $(document).on("submit", "form#user-login", function(e){ e.preventDefault(); var emailAdd = $("#edit-pass").val().replace(/ / ...

Error message "The camera provided is invalid and not an instance of THREE.Camera" appears when attempting to render a cube using Three.js

I've been working on a small "engine" project using three.js to easily create and position objects. So far, I have set up the scene, renderer, and camera successfully. However, when attempting to render and attach a cube to my scene, I encounter an is ...

Exploring the world of three-dimensional graphics with the power of HTML5, canvas,

Here is the HTML markup I am working with: <canvas id="container" name ="container" width="300" height="300"></canvas> This is the JavaScript code: var WIDTH = 400, HEIGHT = 300; var VIEW_ANGLE = 90, ASPECT = WIDTH / HEIGHT, NEAR = 1, FAR = ...

The custom directive in Vue utilizes the refreshed DOM element (also known as $el)

I am looking to create a custom directive that will replace all occurrences of 'cx' with <strong>cx</strong> in the Dom Tree. Here is my current approach: Vue.config.productionTip = false function removeKeywords(el, keyword){ i ...

Invoke an Angular service from a separate JavaScript file

I have a few javascript and html files: User.js, index.html, Door.js I am looking to utilize a function in the User.js file. Link to my user.js file Link to my door.js file I am trying to call the getUserInfo function from User.Js within the Door.j ...

Customizing Form Inputs in ReactJS using Props Array

Trying to wrap my head around handling a dynamic number of props data for a form. Despite searching high and low on Google, I've come up empty-handed. I am gathering data on the number of appointments based on the number of dogs owned by a user. So, t ...

Are you ready to dive into the world of running an ASP.NET MVC project with Angular in Visual Studio

Currently, I am working on developing a CRUD application using ASP.NET MVC in Visual Studio with Angular. I am interested in running the entire project solely through VS Code without relying on Visual Studio. Does anyone have a solution for achieving thi ...

Can I construct an html table-esque layout employing fabric js?

https://i.stack.imgur.com/Zwkj3.jpg I'm in the process of developing a schema builder inspired by vertabelo. To achieve this, I've opted to utilize fabric.js for its interactive features. My main challenge lies in creating an HTML table-like str ...

Internet Explorer 11 XHR Troubles

Our company has successfully developed a JavaScript video player that can be embedded on various websites using a script tag. As part of the bootstrapping process, we utilize XMLHttpRequest to fetch resources from our server. This creates cross-origin requ ...

Modify an element on one webpage using a function called from another webpage

I am currently working on a website design that involves displaying images on various frames. While I have managed to change content across different frames, I am now exploring the possibility of changing content across different web pages. Here is the se ...

What is the syntax for declaring a function type with an optional parameter in Typescript?

I have a function with optional parameters that I am passing down to another component. execute = (option: string = 'default'): void => { // ... } In the receiving component, there is a property called executeFunction where I intend to assi ...

FusionMaps XT integration with VueJs: Troubleshooting connectorClick events issue

I am experiencing some issues with events connectorClick on my VueJS processed map. When I click on the connector line in the example below, the alert function does not seem to work as expected. Vue.use(VueFusionCharts, FusionCharts); let grphMap = new ...