Steps for setting up a nested route in Angular 2

I am currently working on a project that includes an admin page (check the file structure below). I am trying to set up a child route named 'createuser' for the admin page (localhost:4200/admin/createuser). Despite my attempts, I encountered an error stating 'Cannot find primary outlet to load 'CreateComponent'.' To address this issue, I included a router-outlet in my admin component html. While this fixed the routing problem, it caused the HTML content from the admin page to display on the 'createuser' page. How can I prevent this overlap? Did I overlook something in my configuration?

admin.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
    moduleId: module.id,
    selector: 'admin',
    templateUrl: 'admin.component.html'
})

export class AdminComponent implements OnInit
{
    constructor(){}
    ngOnInit(){}
}

admin.component.html

<router-outlet></router-outlet>
<div class="logo" style="background-color: #fbc111">
    <img src="../../../assets/lbtrackerlogo.png" style="width: 250px;padding: 15px">
    <button class="btn btn-default" routerLink="create" style="position: absolute;top:25px;left: 80%">Create Agency</button>
</div>

create.component.html

<h1>Create Component</h1>

create.component.ts

import { Component, OnInit } from '@angular/core';
import { AngularFire, AuthProviders, AuthMethods, FirebaseListObservable } from 'angularfire2';
import { Router } from '@angular/router';
import { UUIDService } from '../../../services/uuid.service';

@Component({
    moduleId: module.id,
    selector: 'create',
    templateUrl: 'create.component.html'
})
export class CreateComponent implements OnInit
{
    constructor() { }

    ngOnInit()
    {
        console.log("In Create component");
    }
}

app.routing.ts

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

import { LoginComponent } from './components/login/login.component';
import { AdminComponent } from './components/admin/admin.component';
import { CreateComponent } from './components/admin/create/create.component';

import { AuthGuard } from './auth.service';

const appRoutes: Routes = [
    {
        path: '',
        component: LoginComponent
    },
    {
        path: 'login',
        component: LoginComponent
    },
    {
        path: 'admin',
        component: AdminComponent,
        canActivate: [AuthGuard],
        data: { roles: ['admin'] },
        children: [
            {
                path: 'create',
                component: CreateComponent
            }
        ]
    }
];

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

https://i.sstatic.net/DsiUT.png https://i.sstatic.net/o3zwP.jpg

Answer №1

To enhance your AdminComponent functionality, consider creating a child route as the default route. Simply duplicate your AdminComponent's code, design, and display into this new child route to ensure smooth operation.

When setting up a child route, think of it like organizing content in HTML. The parent container retains its original information, and the child route introduces additional content without removing anything from the parent.

Your route structure could resemble the following:

Admin - /admin - automatically directs to AdminDefaultController
    AdminDefaultController - /admin/dashborad 
    AdminCreateController - /admin/create

Answer №2

Ensure that the <router-outlet> is placed within your app.component.html in order to prevent such undesired behavior.

Don't overlook adding CreateComponent to your app.module.ts. Double check that CreateComponent is included in your module's declarations.

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

Using {children} in NextJS & Typescript for layout components

I am looking to develop a component for my primary admin interface which will act as a wrapper for the individual screens. Here is the JavaScript code I have: import Header from '../Header' function TopNavbarLayout({ children }) { return ...

Is it possible to transfer the setState function between different contextProviders?

I'm encountering difficulties in setting a state when passing the context provider to other elements. Here is my code snippet. I have created a FancyboxContext so that I can easily access it from anywhere in the app. import React, { createContext, use ...

Defining Multiple Types in Typescript

I have created an interface in a TypeScript definition file named d.ts: declare module myModule { interface IQedModel { field: string | string[]; operator: string; } } In an Angular controller, I have utilized this interface like ...

Exploring an array within an object using Typescript and React

As a newcomer to TypeScript and React, I have a project where I need to extract data from a JSON file (back-end) and display it on cards (front-end). I am trying to pass props using cards?.items.map, but I'm uncertain about the correct way to access ...

cycle through options of radio buttons

How can I display items of radio buttons, with the values of these items coming from a backend api? <div class="input-group col-md-9 input-group-sm"> <label>gender</label> </div> <!-- TO CORRECT ...

How can the ordering of dynamically generated components be synchronized with the order of other components?

Currently, I'm delving into Vue 3 and encountering a specific issue. The tabs library I'm using only provides tab headers without content panels. To work around this limitation, I've come up with the following solution: <myTabs/><!- ...

Encountering an issue connecting to the backend server for the

I am attempting to make a POST request from my Angular 2 frontend to my Spring backend, but I am encountering an error. The error message: GET http://localhost:8080/loginPost 405 () Failed to load http://localhost:8080/loginPost: No 'Access-Control ...

The Angular Universal Starter is running smoothly on local environments, but encountering difficulties when attempting to launch on the

My current challenge involves running Angular Universal Starter on a Centos server. Executing build:ssr and serve:ssr locally works without any issues. After transferring the dist folder to the server, I updated nodejs, npm, and pm2 to their latest ver ...

Newly added rows do not automatically refresh in Angular's mat-table

(Angular 8) I am working with two components, addgame and home. In the home component, I am displaying all games stored in the database using a REST API. Within the home component, I am calling the game component in a dialog view using Mat-dialog. The i ...

What could be causing my TypeScript code to not be recognized as CommonJS?

I rely on a dependency that is transpiled to ES6. My goal is to leverage ES2019 features in my own code. Ultimately, I aim to output ES6. This is how I set up my tsconfig { "compilerOptions": { "module": "CommonJS" ...

ways to display selected custom information with a choiceLabel in a dropdown using primeng

Is there a way to display custom data on a dropdown in Primeng while also showing the selected data as shown in the dropdown list? Please refer to both images below for clarification. <div class="p-grid" *ngIf="deleteUser" style=&quo ...

Difficulty arises when attempting to load Silverlight within an Angular2 component

Issue with Silverlight Component Loading When embedding and loading the Silverlight.xap file directly inside an HTML page, everything works perfectly. However, when we move the same code inside a component, the Silverlight content fails to load. Interest ...

Ways to simulate a function that is a part of an internal object

Is there a way to mock a method from an object within my UnderTest class? When the Update method is triggered by an event from a child component, I need to mock the service.saveNewElement(data) method in order to test data in the then() block. <script ...

Is there a way to denote a specific part of a generic type without explicitly specifying the parts as generics themselves?

My dilemma involves an object defined by a type from a 3rd party library: // Unable to modify this - it belongs to the 3rd party library; interface TypedEvent< TArgsArray extends Array<any> = any, TArgsObject = any > extends Event { args ...

Customizing the entire application's style based on conditions in Angular 4

Looking to implement a dark mode button for the app. Create a toggle switch for "dark mode". This switch will change a boolean value, "dark-ui", between true and false. When the app component detects dark-ui as true, add the class "dark" to a parent-leve ...

I'm puzzled as to why I have to encode the path parameter twice in order for the REST call to properly handle special characters

I have a challenge with a REST call that fetches a product's ingredients using the product name as the path variable. I allow for any character to be used, and I know I need to use encodeURIComponent(name) to encode characters such as "/" to prevent m ...

Best practices for managing CSV files in Next.js with TypeScript

Hello, I am currently working on a web application using nextjs and typescript. One of the features I want to implement is a chart displaying data from a csv file. However, I am not sure if using a csv file is the best choice in the long run. I may end up ...

An error occurred while trying to upload the image: Undefined property 'subscribe' cannot be read

Recently, I implemented a create post function that allows users to fill in the title, content, and upload an image. However, I encountered an issue where the progress bar fills up and the image gets uploaded to Firebase successfully, but it doesn't a ...

What is the best way to display various tables depending on the grouping of a specific row value?

Recently, I came across some interesting JSON data that looks like this: [ { "fruit":"apple", "country": "A" }, { "fruit":"banana", "country": "b" }, { "fruit":&q ...

The TypeScript find() method on an array are showing an error message that says, "There is no overload that matches this call

Issue Description I encountered a problem while using TypeScript's find() method for an array. Whenever I input a value, it does not work properly and displays an error message stating, "No overload matches this call". Code Snippet addOption(event: ...