Creating dynamic Angular child routes with variable initial segment

Recently, I've been working on a new project to set up a blogging system. The next step in my plan is to focus on the admin section, specifically editing posts.

My idea for organizing the routes is as follows:

  1. /blog - Home page
  2. /blog/:slug - Accessing individual posts
  3. /blog/admin - Admin section access

These are the current routes I have implemented:

const routes: Routes = [
  {path: '', component: BlogHomeComponent},
  {path: 'admin', component: BlogAdminComponent},
  {
    path: ':slug', component: PostComponent,
    children: [
      {
        path: 'edit',
        component: PostEditComponent
      }
    ]
  },
];

Now, I am focusing on setting up the 'edit post' section. My idea is to create a route like this:

/blog/:slug/edit

With this setup, the URL structure could look something like: /blog/post-title-thing-im-talking-about/edit

This way, I can easily add /edit at the end of each post URL to edit it.

However, the current routing setup is not functioning correctly. It tries to load the page and then redirects out of the blog module to the projects module, resulting in a route like:

/blog/projects

Here are the main routing instructions in my app.module:

const routes: Routes = [
  {
    path: 'blog',
    loadChildren: './blog/blog.module#BlogModule'
  },
  {
    path: 'projects',
    loadChildren: './projects/projects.module#ProjectsModule'
  },
  {path: 'contact', component: ContactComponent},
  {path: '', component: HomeComponent}

];

I suspect that the issue lies in the fact that the system is looking for a URL pattern like "/blog/blog-post-title/edit" instead of matching /blog/***/edit. I have experimented with different routing setups, but encountered errors such as:

"'/blog/blog-post-name-thing/edit' does not exist as a current route."

Is there a way to implement dynamic routing in this scenario?

Answer №1

In order to properly configure the setup, you should ensure that the edit component is not displayed within the template of the PostComponent. Instead, it should be on a separate page. To achieve this, your routes should look like:

const routes: Routes = [
  {path: '', component: BlogHomeComponent},
  {path: 'admin', component: BlogAdminComponent},
  {path: ':slug', component: PostComponent},
  {path: ':slug/edit', component: PostEditComponent}
];

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

The color attribute for the ion-button element is not functioning properly on Android devices in

In my app, it functions correctly when running on iOS, but encounters issues when running on Android. The problem lies in the color attribute not working on buttons and other elements on Android. Removing the attribute makes them visible, but the desired s ...

Experiencing a lengthy installation process of TypeScript on Node.js

I attempted to set up TypeScript on my laptop running MS Windows 8.1 (64-bit). After installing Node.js 64-bit, I ran the command npm install -g typescript. However, the installation appeared to stall with a spinning '/' for over 2 hours. When I ...

How should a child component specify the type of component being passed in props?

Consider the following snippet from App.tsx : <Layout header={ <Header/> } </layout> Now, let's take a look at the Layout component : export default function Layout({header, body}: any) { return ( <div className="layou ...

Angular resolver does not return anything if the outcome is an observable generated using the .asObservable() method

While working on my project, I wanted to simulate my http calls by using a BehaviorSubject along with Observable properties in my resolver service. However, I faced an issue and I am not sure why this code snippet is not functioning as expected: schedule- ...

Issue: Unable to find solutions for all parameters in NoteService: (?)

After following a tutorial on Angular 2 from , I encountered the mentioned error when running my API. The browser indicates that there are unresolved parameters in the following service: import {Injectable} from '@angular/core'; import { ApiSe ...

Is there a way to change the font size with a click in JavaScript or Angular?

Here is a breakdown of the 4 steps: 1.) Begin by clicking on a category 2.) The filtered products will be displayed 3.) Select the desired products from the filter 4.) Once selected, the products will appear in the rightmost part of the screen within t ...

Attempting to create a promise for a dropdown menu in React-Select

I am facing an issue here: type Person = { value: string; label: string; }; Furthermore, I have a promise-containing code block that fetches data from an API and transforms it into the appropriate array type for a React component. My intention is to r ...

Why is it that the game board component is not appearing on my HTML page?

I am currently facing an issue with a loop in my Angular html file: <div class="board" #board> <div class="row" *ngFor="let row of this.board; let i = index"> <div *ngFor=" ...

Tips on sending component values to Host Listener in Custom Directives using Angular 2

I am looking to transmit model values from my HTML template to a custom directive: @Directive({ selector: '[eventlistener]' }) export class EventListener { @Input() value:string = 'Not Defined'; @HostListener('click& ...

typescript extending a type from a higher-level interface

Consider the TypeScript interface provided below: export interface Update { type: 'STATUS_UPDATE'; } I am interested in extending this interface by adding one more value to the type property, as shown here: export interface HttpUpdate extends ...

Tips for incorporating ngIf within a td element

My dilemma is with a table I have that displays data from a database. I need to be able to edit the data based on certain qualifications, so I want to include two buttons - one for deleting and one for editing. These buttons should only be enabled if the r ...

Is there a way to integrate the AuthState TypeScript Interface into the react-oidc-context Node package for testing in Next.js?

We are currently working on a Next.js application that utilizes the react-oidc-context Node module for authentication with ADFS. During our testing phase using Vitest, we encountered the following error: TypeError: Cannot read properties of undefined (rea ...

Verification of custom data type validation

I am puzzled by the behavior of this custom type state: interface DataType { [key: string]: string;} const [data, setData] = React.useState<DataType>({}); When I attempt to execute console.log(data === {}) It surprisingly returns false. Why ...

Using a BehaviorSubject in conjunction with ngIf can rearrange the placement of elements

I am facing an issue with the placement of my HTML tags. Here is a snippet from my service: public showExportCsvModal = new BehaviorSubject<boolean>(false); public showDownloadModal = new BehaviorSubject<boolean>(false); And here is how it loo ...

Issue: (SystemJS) XHR error (404) encountered in Angular2 Plnkrsandbox

The issue: https://i.sstatic.net/jUKBU.png https://plnkr.co/edit/910M73kwYKc8xPlSIU57?p=preview index <!DOCTYPE html> <html> <head> <base href="/"> <title>Angular 2.1.2 + TypeScript Starter Kit</title> <met ...

Angular application automatically adding 'localhost' before the backend API endpoint

After migrating my backend to AWS, the backend URL is functioning correctly in Postman. However, when I use the backend URL in an Angular service, 'localhost' is being added to the front of it. How can I resolve this issue? Backend URL: api.an ...

Is it time to end my MediaObserver subscription in flex-layout for Angular?

Within my Angular component, I have implemented the following code to display different elements based on screen resolution: constructor(private mediaObserver: MediaObserver) {} private mySubscription: Subscription; public ngOnInit(): void { this.my ...

What strategies can be used to address inconsistencies between the type system and runtime behavior?

I have created a unique TypeScript type called Awaitable<T> with the goal of ensuring that Awaited<Awaitable<T>> is always equal to T. export type Awaitable<T> = | (T extends Record<'then', Function> ? never : T) ...

Functionality not functioning within Shadow DOM

After creating and exporting an Angular Element as a single script tag (user-poll.js), using the element on a host site is simple. Just include the following two lines: <user-poll></user-poll> <script src="path/to/user-poll.js"></sc ...

Unable to retrieve input value in ReactJS with TypeScript

I've just started learning Typescript and I encountered an error while trying to console.log the input field value. Any tips or suggestions on how to handle this? Here's my code: class Register extends Component<{},userState> { state = { ...