Establish a new subpage that can have multiple main pages

I am currently working on implementing a navigation feature in an Angular application. I want to be able to access the same page from different "parent" pages while maintaining the navigation bar's awareness of the origin page.

For navigation, I am utilizing routerLinkActive="active". In my application, I have two pages, "Favorites" and "All users," both displaying lists of users. Each user has a details page accessible through users/userId.

My goal is to ensure that when a user navigates to the details page from the "Favorites" list, the "Favorites" menu button remains active in the navigation bar. Similarly, when navigating from the "All users" list, the "All users" button should stay active.

Here is how my routes are currently set up:

const routes: Routes = [
{
  path: 'favorites',
  component: FavoritesComponent
},
{
  path: 'all',
  component: AllUsersComponent
},
{
  path: 'user/:id',
  component: UserDetailComponent,
}

Currently, when navigating to the user/id page, neither "favorites" nor "all" remains "active" in the navigation bar as intended.

Answer №1

If you want to use the same component for both the favorites and all main routes, you can achieve this by setting up a child route structure. The key is to have an empty route path leading to the main component for each route, followed by detail routes under each main route. Your route configuration should be structured like the example below:

const appRoutes: Routes = [
  {
    path: 'favorites',
    children: [
      {
        path: '',
        component: FavoritesComponent
      },
      {
        path: 'user/:id',
        component: UserDetailComponent,
      }
    ]
  },
  {
    path: 'all',
    children: [
      {
        path: '',
        component: AllUsersComponent
      },
      {
        path: 'user/:id',
        component: UserDetailComponent,
      }
    ]
  },
  {
    path: 'user/:id',
    component: UserDetailComponent,
  },
  { path: '**', redirectTo: "/all" }
];

By configuring your routes as shown above, the favorites and all links will work as expected.

Check out this StackBlitz example for reference!

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

Unable to bring in the directive from the Angular library

I've created this custom Directive within my library: @Directive({ selector: '[layoutHeaderTitle]', standalone: true }) export class HeaderDirective { constructor( readonly tpl: TemplateRef<any>, private re ...

Having trouble modifying the value of a textBox with ngModel and a directive

Having trouble trimming a text input and ending up with duplicate values https://i.sstatic.net/PkrxB.png New to Angular, seeking help in finding a solution View Code on StackBlitz ...

Incorporate matTooltip dynamically into text for targeted keywords

I'm currently tackling a challenge in my personal Angular project that utilizes Angular Material. I'm struggling to find a solution for the following issue: For instance, I have a lengthy text passage like this: When you take the Dodge action, ...

Reactive form loses preloaded data due to ExpressionChangedAfterItHasBeenCheckedError when modal is dismissed

Within my project, I have a sidenav that contains various links. One of these links directs to a component that presents some input data. Below is the TypeScript code: @Input() data: MyData; myModal: BsModalRef; editForm: FormGroup; ngOnInit(){ this. ...

Next.js is displaying an error message indicating that the page cannot be properly

Building a Development Environment next.js Typescript Styled-components Steps taken to set up next.js environment yarn create next-app yarn add --dev typescript @types/react @types/node yarn add styled-components yarn add -D @types/styled-c ...

Tips on designing unique field validation decorators in NestJS using GraphQL

I'm currently developing a NestJS API using apollo-server-express and have created an InputType for appointments as shown below: @InputType() export class AppointmentInput { @Field(of => String) @IsNotEmpty() name: string; @Field(o ...

Exploring the MVVM architecture in React and the common warning about a missing dependency in the useEffect hook

I'm currently in the process of developing a React application using a View/ViewModel architecture. In this setup, the viewModel takes on the responsibility of fetching data and providing data along with getter functions to the View. export default f ...

Discovering the ins and outs of utilizing Validator.pattern in Angular 9

BGroup = new FormGroup({ test: new FormControl(null, [Validators.required, Validators.pattern("[0-9]*$")]) }); Greetings! I am currently using Angular 9 and I have a question. How can I define a pattern that only accepts decimal numbers? Speci ...

Pass the chosen value from an Angular material select component to a specified function

I'm having trouble figuring out how to pass the selected value to a function in a mat-select without using ngModel. In the desktop version of my app, I have a list with clickable items, but on the iPad version, I am using a mat-select element. In the ...

"Upload a video file and use JavaScript to extract and save the first frame as an image

I have a webpage where users can upload a video file, and the page will generate a thumbnail based on a timestamp provided by the user. Currently, I am focusing on generating the thumbnail from the FIRST frame of the video. Here is an example of my progr ...

Create a package themed with Material UI for export

I am attempting to create a new npm package that exports all @material-ui/core components with my own theme. I am currently using TypeScript and Rollup, but encountering difficulties. Here is the code I have: index.ts export { Button } from '@materia ...

Unable to bind to property as it is not recognized as a valid attribute of the selector component

I have a situation where I need to pass a variable from one component to another using @input. Here is my parent component : @Component({ selector: 'aze', templateUrl: './aze.component.html', styleUrls: [('./aze.compo ...

The Power of Angular Pipes and TypeScript Type Guards

After researching about type guards in TypeScript at this source and this source, I still encountered compiler errors. Error:(21, 14) TS2349: Cannot invoke an expression whose type lacks a call signature. Type '{ (callbackfn: (value: Foo, index ...

Angular 7 flex layout ensures that the table fills its parent container completely without overstretching it

Hello, I'm encountering a problem with the sample found on StackBlitz. My goal is to confine the table to one page and have the remaining height filled after the header. If the table exceeds this height, I would prefer it to be hidden. However, based ...

Tips on preventing pooling in Angular 5

service.ts: // Fetch all AgentLog logs using pooling method getAgentLogStream(): Promise<string> { const url = `${this.testCaseUrl}/logfile`; return Observable .interval(5000) .flatMap((i)=> this.http.get(url).toPromise().then(respons ...

Why does "excess property checking" seem pleased when I utilize a key from set A or set B, even though "keyof (A|B)" is consistently "never"?

I am diving deeper into Typescript types and encountering some puzzling behavior: interface Person { name: string; } interface Lifespan { birth: number; death?: number; } let k: keyof (Person | Lifespan); //k is never let test1: Person | Life ...

Storing a Vue/JS element reference in a constant using Typescript

In my template, I have one form element and one button element: <button type="submit" id="ms_sign_in_submit" ref="submitButton" class="btn btn-lg btn-primary w-100 mb-5"> </button> Wi ...

Unable to retrieve a string from one function within another function

Three functions are responsible for triggering POST API calls, with the intention of returning a success or failure message to whoever invokes them (Observable<string>). In an effort to avoid repetition, I introduced a new function to retrieve succe ...

No bugs appeared in Next.js

I am currently in the process of migrating a large create-react-app project to NextJS. To do this, I started a new Next project using create-next-app and am transferring all the files over manually. The main part of my page requires client-side rendering f ...

Angular2 app is sending empty HTTP headers to the server

My REST api, built using SpringBoot, incorporates JWT for authentication and authorization. To achieve this, I utilize a FilterRegistrationBean. Within this setup, there exists a class called JwtFilter that extends GenericFilterBean. This class is respons ...