Error in Angular 2 (CLI) Routing: Unable to process (Error reading property 'split' of undefined)

What could be the reason why routing is only working for the first imported component after AppComponent (for example, "PageNonFound")? I also encountered an error after implementing routing in my project.

Error

Error in ./AppComponent class AppComponent - 
inline template:13:42 caused by: 
Cannot read property 'split' of undefined

App.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule, Routes } from '@angular/router';

import { AppComponent } from './app.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { HomeComponent } from './home/home.component';

const appRoutes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: '**', component: PageNotFoundComponent },
  { path: 'home', component: HomeComponent }
];

@NgModule({
  declarations: [
    AppComponent,
    PageNotFoundComponent,
    HomeComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forRoot(appRoutes)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

App.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'testing';
}

App.component.html

<nav class="nav navbar navbar-custom navbar-fixed-top" role="navigation">
  <div class="container-fluid">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" [routerLink]="['/home']">Test</a>
    </div>
    <div>
      <div class="collapse navbar-collapse" id="navbar">
        <ul class="nav navbar-nav">
          <li><a [routerLink]="['/home']" [routerLinkActive]="active">Home</a></li>
        </ul>
      </div>
    </div>
  </div>
</nav>
<router-outlet></router-outlet>

Vers:

angular-cli: 1.0.0-beta.28.3
node: 6.9.4
os: darwin x64
@angular/common: 2.4.9
@angular/compiler: 2.4.9
@angular/core: 2.4.9
@angular/forms: 2.4.9
@angular/http: 2.4.9
@angular/platform-browser: 2.4.9
@angular/platform-browser-dynamic: 2.4.9
@angular/router: 3.4.9
@angular/compiler-cli: 2.4.9

Answer №1

try using routerLinkActive="active"

or

[routerLinkActive]="['active']"

and adjust the order of your routes

const appRoutes: Routes = [
  { path: 'dashboard', component: DashboardComponent },
  { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
  { path: '**', component: NotFoundComponent }, 
];

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

Clicking on the icon image that features a Background Video will trigger the video to play in a popup window originating from the same location

A background video is currently playing on the site. When the play icon is clicked, the video should start playing in a popup. The video should start playing continuously from the exact moment and position where it is clicked. Check out the example here. ...

Challenges with synchronizing Highcharts horizontally

I have been working on implementing synchronized charts in my application by using the example code provided by Highcharts here. My layout consists of columns created with the Materialize framework, and I placed the charts side by side in a row. However, I ...

service.js was identified as registered, however, it did not run as expected

I clicked on this link for my angular 2.0 tutorial journey. I managed to successfully display the list of drugs, but encountered an issue when I attempted to create the AuthorComponent. Unfortunately, my app stopped running due to the following error: Er ...

Attempting to trigger the timer to begin counting down upon accessing the webpage

Take a look at this example I put together in a fiddle: https://jsfiddle.net/r5yj99bs/1/ I'm aiming to kickstart as soon as the page loads, while still providing the option to pause/resume. Is there a way to show the remaining time as '5 minute ...

Question about Looping Concept

var answer = ""; var correct = "4"; var question = "What is 2 * 2?"; for(i = 2; i < 5; i++) { answer = prompt(question, "0"); if (answer == correct) { alert("Your answer is correct!"); break; } } Before the break command is ...

Eliminate the jQuery function call in JavaScript

I am working with a file.js that looks like this: // TICautocapture.js var TICautocapture = (function(){ var lib = {...} var error_handler; var handleError = (error_code, error_callback) => {...} function autocapture(container, options){...} ...

Error encountered when trying to use the .find function in Typescript: "The expression is not callable."

Environment Details: typescript 4.5.5 Error Summary An issue occurred stating: "This expression is not callable. Each member of the union type '{ <S extends User>(predicate: (this: void, value: User, index: number, obj: User[]) => value ...

Ways to enhance focus on childNodes using Javascript

I am currently working on implementing a navigation system using a UL HTML Element. Here's the code I have so far: let htmlUL = <HTMLElement>document.getElementById('autocomplete_ul_' + this.name); if (arg.keyCode == 40) { // down a ...

Tips for triggering a click event automatically after a 2-minute delay in ReactJS using TypeScript

I need assistance automating a button's onClick function to execute after a 2-minute delay. The current button invokes the handleEventVideos() function. What is the best way to automatically trigger the button click after 2 minutes? I had tried creat ...

What is causing the TypeError in Discord.js when trying to read the 'voice' property? Any help troubleshooting this issue would be greatly appreciated

Hey everyone, I'm having an issue with my play.js file that I obtained from a Source Bin. If anyone could provide some assistance, it would be greatly appreciated. const ytdl = require("ytdl-core"); const ytSearch = require("yt-search"); //Global que ...

Conflict arises in the path of merging (Angular)

Hi there, Encountering a merge conflict on the path "/src/app/employee.service.ts". while executing the following command ng generate service employee --skipTests=true I am using Ubuntu 20.04 as my operating system and have spent an hour sear ...

NEXT.JS - LocalStorage unexpectedly resets data to its initial state instead of persisting changes after the page is refreshed

Upon initial component run, "1" is displayed. Clicking the button appends it by 3 successfully. The value inside local storage also updates accordingly. However, upon reloading the page, the local storage reverts back to 1. What could be the missing piec ...

Strategies for testing a split get() function using expressJS and jestJS to streamline unit testing

How can I define a get() route in an Express.js application for easy unit testing? To start, I extracted the get() function into its own file: index.js const express = require('express') const socketIo = require('socket.io') const Gp ...

One required positional argument is needed in `update_one()`: 'update' is missing

I've exhausted all possible options, but I can't seem to make it work. Any suggestions on how I can get this code to function properly? I attempted using ajax_data to update the values, but it was unsuccessful. The main goal of this code is to al ...

Array fed with Mongoose query

Currently experiencing challenges with a section of my code. I am utilizing Mongoose to retrieve data from my database, where I intend to push a portion of that data into an array titled 'authors' for further manipulation. Although I am able to ...

Using Jquery for a synchronous "Ajax" request doesn't seem to be functioning

As a newcomer to javascript, I am currently in the process of developing a react/flux app and utilizing jquery for synchronous "ajax" calls (sjax?) to the backend. However, I am encountering inconsistent behavior which seems to be caused by my ajax call no ...

Invoking method in Angular component upon receiving a notification via ActionCable

Currently, I am practicing the utilization of ActionCable within Angular. To begin, I set up a rapid Rails application on Heroku, followed by creating an Angular application with the actioncable npm module integrated as a dependency. For experimentation p ...

Javascript - understanding variable scope

Hey there! I have some code that I need help with var idx = 0; var size = 0; do { response.push({ key: "data" + idx, ajaxOptions: function () { var data = this.getPref("groupsCN"); var items = data.split('; ...

Error occurred when trying to import an external module using an invalid hook call

I am creating a package named "Formcomponent" using React and React Bootstrap. This code is from index.tsx /** * Renders a component for a form. */ import React from "react"; import Form from "react-bootstrap/Form"; /** * List of props * @returns */ ...

After refreshing once, encountering difficulty in accessing authorization.user._id

After utilizing a Yo generator, I created a NodeJS app (MeanJS). There seems to be an issue with the authentication module. When trying to retrieve the authentication.user._id value in the HTML page using {{authentication.user._id}}, it displays correctly ...