Optional URL parameters in Angular 8 allows for dynamic and flexible routing

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

import { LayoutComponent } from './layouts/layout.component';

const routes: Routes = [
  {
    path: '',
    component: LayoutComponent,
    children: [
      {
        path: ':id',
        loadChildren: './layouts/layout.module#LayoutModule'
      }
    ]
  },
  {      /* THE FOLLOWING BLOCK WORKS */
    path: '',
    component: LayoutComponent,
    children: [
      {
        path: '',
        loadChildren: './layouts/layout.module#LayoutModule'
      }
    ]
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes, {
    scrollPositionRestoration: 'enabled'
  })],
  exports: [RouterModule]
})
export class AppRoutingModule { }

I am attempting to create two different sets of URLs with the same layout structure. The first URL works fine at http://localhost:4200/account. However, when trying to access the second URL at http://localhost:4200/20/account, it fails and displays the error message:

core.js:5882 ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: '20/account'

I'm unsure where I made a mistake, can anyone assist me with this?

Answer №1

Remove the path ':id' and pass parameters to the constructor:

  public constructor(
        private path: ActivatedRoute,
        private navigator: Router,
        injector: Injector
    ) {
        super(injector);
        this.path.params.subscribe((param) => {
            this.filterId = [Number.parseInt(param.id)];
            if (param.id) {
               this.fetchData();
            }
        });      
}

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 2 applications with routing capabilities running within nested iframes

Currently, I am in the process of developing an Outlook add-in using Angular 2. Since it is an outlook hosted app, it will be run within a cross-domain iframe and I have no control over this setup. The iframe is also sandboxed with specific properties incl ...

The variable 'x' is being referenced before being initialized

Having trouble understanding the tsserver error in this static method from the Logger class. LogLevel const enum LogLevel { ERROR = 0, WARN = 1 } export default LogLevel; Logger static defaultHandler(level: LogLevel, ...message: readonly ...

The error in Angular states that the property 'length' cannot be found on the type 'void'

In one of my components, I have a child component named slide1.component.ts import { Component, Input, OnInit, EventEmitter, Output } from '@angular/core'; @Component({ selector: 'app-slide1', templateUrl: './slide1.component. ...

Develop a personalized Angular module utilizing ngx-translate functionality

I recently developed my own personal Angular library filled with various components to streamline my projects. I followed a helpful tutorial to create the library successfully. Testing it in another project went smoothly. Now, the challenge is incorporati ...

Content not displaying in Angular Material Tab (mat-tab)

Incorporating Angular Material tabs into my Angular 5 project has been quite the challenge. I am attempting to use the tabs as a submenu on a links page, where numerous links are categorized into smaller sections that will be displayed when selected from t ...

Is the Angular Library tslib peer dependency necessary for library publication?

I have developed a library that does not directly import anything from tslib. Check out the library here Do we really need to maintain this peer dependency? If not, how can we remove it when generating the library build? I have also posted this question ...

Angular 2 experiencing issues with the authorization header

Hello there! I am currently working with the Ionic 2 framework alongside Angular, and I'm facing an issue while trying to make an HTTP request with the authorization header. It seems like the header is not being sent properly. Can someone help me iden ...

What is the best way to retrieve information from a mat-option loop?

Utilizing mat-select to fetch options from a database, the table also includes an images column. How can I change the image outside of mat-select when the mat-option is changed? I am attempting to extract the value outside of the mat-option loop. I have ...

When trying to import a CSS URL in Angular, the error "expectedcss(css-rparentexpected)" occurred

When working in VS code, I encountered a red error mark in the css file next to "400italic". How can I resolve this issue? Error:- ) expectedcss(css-rparentexpected); .css @import url(https://fonts.googleapis.com/css?family=Roboto:400, 400italic, 600 ...

The FormGroup instance does not return any input method when using the get input function

I am facing an issue where a custom error message should only display if the input for foo is invalid. However, it seems like the line of code myForm.get('foo') is returning null. Below is the simplified version of component.html: <form [for ...

Creating a dynamic web application using Asp .NET Web Api, MVC, and Angular 2, integrating an action that

Working on an ASP .NET MVC application integrated with Angular 2, I encountered a problem when trying to communicate from the angular service to a WebApi Controller. The issue arises when attempting to access an action within the WebApi Controller that req ...

Angular FlexLayout MediaObserver: How to determine the active width using a specific div?

I am currently working on customizing the behavior of fxFlex. The web application I am working on has the capability to function as a standalone version, occupying the full screen of a web browser, as well as being embedded as a web component. It is design ...

When executing prisma generate, an error of TypeError is thrown stating that the collection is

While using typescript with Prisma, I encountered an issue when trying to run prisma generate, as it kept throwing the following error: TypeError: collection is not iterable. at keyBy (/node_modules/@prisma/client/generator-build/index.js:57685:21) at ...

Having trouble with clearInterval in React TypeScript?

I have been encountering issues with the clearInterval function in TypeScript for React. I am not sure why the interval is not being cleared. To address this problem, I defined a variable let interval_counter;, and used it as follows: interval_counter = ...

Is it possible to establish a condition for the component selector in Angular 2/4?

Is there a way to set conditions for a component selector? For example, let's say I have two simple components: First: @Component({ selector:'app-first' templateHtml: 'first.html; }) export class ...

Interactive tabs featuring components selected by the user's clicks

I am currently working on setting up a dynamic tab system that allows components to register themselves with a title. The first tab serves as an inbox, offering numerous actions and link items for users to choose from. Each click on an action or link shoul ...

Efficiently transferring input to a Typescript file

Is there a better way to capture user input in Angular and pass it to TypeScript? <form > <input #input type="text" [(ngModel)]="inputColor" (input)="sendInput(input.value)" /> </form> The current method involves creating a ...

Got a value of `false` for an attribute `closable` that is not meant to be a

Here's the code snippet I have: import { Modal } from "antd"; import styled from "styled-components"; export const StANTModal = styled(Modal)` & .ant-modal-content { border-radius: 20px; overflow: hidden; } `; And ...

I am encountering an issue where the nested loop in Angular TypeScript is failing to return

I am facing an issue with my nested loop inside a function. The problem is that it is only returning the default value of false, instead of the value calculated within the loop. Can someone please point out what I might be doing incorrectly? Provided belo ...

Creating a pop-up effect for a div in the center of a table cell using HTML and CSS

I am currently working with Angular and facing a challenge where I need to display a div like a popup in a table cell when clicked. Despite having the click event logic in place, I am unsure of how to achieve this without using external libraries such as B ...