Creating a Route in Angular 2 for a Component other than the one initialized with the bootstrap function

I am currently in the process of working on a project involving Angular2. If you are interested in understanding why I need to do what I am about to explain, please take a look at this issue.

The main component in my project is called AppComponent and it is bootstrapped using bootstrap. It is a simple component with the following structure:

@Component({
    selector: 'app-view',
    directives: [ Devtools, MainComponent ],
    template: `
        <ngrx-devtools></ngrx-devtools>
        <main-cmp></main-cmp>
    `
})
export class AppComponent { }

Within this component, there is another component called MainComponent (accessed via the main-cmp selector) where I want to configure my routing for specific reasons.

Below is the code implementation:

@Component({ 
    selector: 'main-cmp',
    directives: [ ROUTER_DIRECTIVES, NavComponent ],
    template: `
        <h1>App</h1>
        <nav-cmp></nav-cmp>
        <router-outlet></router-outlet>
    `
})
@RouteConfig([
    { path: '/home',    name: 'Home',   component: HomeComponent,   useAsDefault: true },
    { path: '/medias',  name: 'Medias', component: MediasComponent }
])
export class MainComponent {
    constructor (private router:Router, private store:Store<AppStore>) {
        router.subscribe(url => store.dispatch(changeUrl(url)));
    }
}

Additionally, MainComponent also incorporates NavComponent, which functions as a basic navigation component.

Despite the setup described above, an issue arises stating:

EXCEPTION: Component "AppComponent" has no route config. in [['Home'] in NavComponent@2:15]
.

However, when I move my routing logic to AppComponent, everything works perfectly fine.

Therefore, my query is: is there a way to implement routing functionality in a component other than the one being bootstrapped?

Thank you :).

Answer №1

It seems that the issue lies in the generate method of the RouteRegistry class, where it is explicitly dependent on the root component, as hardcoded in the source code:

The error occurs due to this specific part of the code:

RouteRegistry.prototype._generate = function(linkParams,
         ancestorInstructions, prevInstruction, _aux, _originalLink) {
  (...)
  var parentComponentType = this._rootComponent; // <----
  (...)

  var rules = this._rules.get(parentComponentType);
  if (lang_1.isBlank(rules)) { // <----
    throw new exceptions_1.BaseException("Component \"" +
      lang_1.getTypeNameForDebugging(parentComponentType) +
      "\" has no route config.");
  }

  (...)
};

This issue indirectly affects the _updateLink method of the RouterLink directive.

Refer to the stack trace below for more insights:

RouteRegistry._generate (router.js:2702)
RouteRegistry.generate (router.js:2669)
Router.generate (router.js:3174)
RouterLink._updateLink (router.js:1205)

For troubleshooting purposes, you can check out the plunkr example I used: Access Plunkr.

Answer №2

Can we try a different approach - setting root as a nested route?

@Component({
  selector: 'app',
  directives: [ ROUTER_DIRECTIVES ],
  template: `
    <router-outlet></router-outlet>
  `
})
@RouteConfig([
  {path: '/...', as: 'Main', component: MainComponent, useAsDefault: true }
])
export class App { }

@Component({ 
    selector: 'main-cmp',
    directives: [ ROUTER_DIRECTIVES ],
    template: `
        <h1>App</h1>
        <router-outlet></router-outlet>
    `
})
@RouteConfig([
    { path: '/home',    name: 'Home',   component: HomeComponent,   useAsDefault: true },
])
export class MainComponent { }

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

What is the best way to ensure a jQuery function runs on duplicated elements?

I have been attempting to construct a webpage featuring cascading dropdowns using jQuery. The goal is to generate a duplicate set of dropdowns when the last dropdown in the current set is altered. I aim for this process to repeat up to 10 times, but I cons ...

What is the best way to trigger click events within a select dropdown using Angular?

I have implemented two buttons (month, year) that trigger different events. Now, I want to replace these buttons with a select element. Can you guide me on how to achieve this? Here is my current code: // Button implementation <button class="menu-butt ...

A guide on lazy loading static JSON in your Angular app

Seeking a solution for lazy loading JSON files in an Angular application. It is my understanding that static content in the assets folder is loaded by default during initial rendering and stored in browser memory. However, I am interested in loading only ...

I am attempting to create a form in NodeJs to search for a user in MongoDB by their telephone number using query routing. However, I am puzzled as to why this is not functioning properly

Can you identify the issue in this code? I am able to retrieve the correct mobile number on the console, but it is not being passed to the query routing on /search_user?mob. <input type="tel" name="message" id="mobile_input&qu ...

Error encountered while making a REST API call in Ajax: Unforeseen SyntaxError: Colon unexpected

I am currently troubleshooting my code to interact with a REST API. My platform of choice is "EspoCRM" and I aim to utilize its API functionalities. The official documentation recommends using Basic Authentication in this format: "Authorization: Basic " ...

Ways to simulate objects in jest

I'm facing an issue while trying to mock a function of an object using Jest and Typescript. Below is a concise version of my code: // myModule.ts export const Foo = { doSomething: () => { // ... does something console.log('original ...

React Native - Invariant Violation: Objects cannot be used as a React Child (Utilizing Node.js for the backend)

Trying to calculate the total sum of orders and their quantity using Node JS on the backend. However, encountering issues with the fetch functions not working properly or missing something unknown. The API works as expected when tested in Postman, but err ...

"Learn the steps to dynamically update the ng-bind value of a single element within an ng-repeat loop by

I'm new to Angular and I'm working on developing a shopping cart. I'm currently facing an issue with adding the 'Added!' value when clicking on the "add to cart" button. Here is my code <div ng-repeat="item in products"> < ...

Have you not heard of the greatness of Selenium before?

I've been trying to automate the process of selecting my shoe size, adding it to the cart, and checking out whenever I visit a sneaker page like FootLocker or FootAction. However, each time I attempt to run the script, I encounter the following error: ...

Choose various selections from a drop-down menu using AngularJs

I am currently working on a project where I need to be able to select multiple options from a dropdown menu. The code snippet for this functionality looks like the following: //Controller $scope.data = [{id: 1, Country: Zambia}, {id: 2, Coun ...

The icon for the weather on openweathermap is currently not displaying

Take a look at what my webpage looks like: http://prntscr.com/dg6dmm and also check out my codepen link: http://codepen.io/johnthorlby/pen/dOmaEr I am trying to extract the weather icon from the api call and display that icon (e.g. "02n") on the page base ...

Issue with MVC framework: AJAX query callback function not functioning properly

Struggling with implementing a basic Jquery Ajax callback: Here is my Jquery code snippet: $(document).ready(function () { $('#btnClient').click(function (e) { e.preventDefault(); var txtClient1 = $('#txtCli ...

Generating random images using Javascript

I am facing some challenges while creating my first custom JavaScript function. My goal is to display three random thumbnails on my webpage by selecting images from a pool of options. However, I am encountering issues with duplicated images and handling s ...

Guide on creating and synchronizing an XML/JSON file that stores beat information (BPM) for audio using JavaScript

Looking to sync Javascript events with the BPM of music for a game similar to "Guitar Hero." We start with: In order to create a track file based on beat detection (with each BPM saved like sheet music), how can it be generated beforehand rather than in ...

MongooseError: Timeout occurred after 10000ms while attempting to buffer the operation `users.findOne()` in a Next.js application

Encountering the "MongooseError: Operation users.findOne() Buffering Timed Out After 10000ms" error in my Next.js app while using Mongoose (^8.2.2) to connect to MongoDB. Using Next.js version 14+ Troubleshooting Steps: 1. Checked MongoDB connection str ...

Selecting a JSON object at random

My data is stored in JSON format. [ ["Apple","A"], ["Orange","O"], ["Grape","G"], ["Kiwi","K"] ] Is there a way to randomly select an array item from this data (e.g. ["Grape","G"])? var letterNum = ""; $.ajax ( { url:"getletter.json" }).done( ...

Attempting to showcase a collection of values, specifically focusing on highlighting the even numbers within the array

const sampleArray = [ 469, " " + 755, " " + 244, " " + 245, " " + 758, " " + 450, " " + 302, " " + 20, " " + 712, " " + 71, " " + 456, ...

Subcomponent in React is not rendering as expected

I have a primary React component with a subcomponent named AttributeInput. To prevent redundancy in my code, I moved some of the logic from the main component to a method within AttributeInput. My attempt at referencing this code looks like this: {this.s ...

What is the best way to fetch all Firebase database IDs using Angular?

Is there a way to fetch all data from Firebase database along with their respective IDs? Currently, I have two functions - getAll() and get(input) that retrieve specific products based on the given ID. However, my current implementation only returns obje ...

How can I obtain the width of one element and then use it to adjust the size of another element that is

Currently, I am working on a dropdown menu and facing an issue with setting the submenus to match the width of the top-level page. In my HTML structure (specifically for a WordPress theme), it looks something like this: <ul class="menu"> <li ...