Angular's routerLink feature has a tendency to direct me to a completely empty page

I recently started developing my first angular app and I have encountered an issue with navigating on my page using routerLink. The welcome component loads up fine, but when I click on a routerLink, it redirects me to a blank page.

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

@Component({
  selector: 'pm-root',
  template: `<nav class="navbar navbar-expand navbar-light bg-light">
    <a class="navbar-brand">{{pageTitle}}</a>
    <ul class='nav nav-pills'>
      <li><a class="nav-link" routerLink='/welcome' routerLinkActive="active">Home</a></li>
      <li><a class="nav-link" routerLink='/products' routerLinkActive="active">Product list</a></li>
    </ul>
  </nav>
  <div class="container">
  <router-outlet></router-outlet>
  </div>`
})
export class AppComponent {
  pageTitle: string = 'Acme Project Mangement';
}

The structure of my app.module.ts file is as follows:

@NgModule({
  declarations: [
    AppComponent,
    ProductList,
    ConvertToSpacesPipe,
    starComponent,
    ProductDetailComponent,
    WelcomeComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule,
    RouterModule.forRoot([
      {path: 'products', component: ProductListComponent},
      {path: 'products/:id', component: ProductDetailComponent},
      {path: 'welcome', component: WelcomeComponent},
      {path: '', redirectTo: '/welcome', pathMatch: 'full'},
      {path: '**', redirectTo: 'welcome', pathMatch: 'full'}
    ])
  ],
  bootstrap: [AppComponent]
  
})
export class AppModule { }

Despite not being able to identify any errors in my code and not receiving any compiler errors, I am unable to proceed with my angular project. Any assistance or guidance would be greatly appreciated.

Answer №1

It seems like the selector pm-root is not defined in the index.html file, possibly a common typo as most developers use app-root instead.

<app-root>loading</app-root>

I tried running your code and the only issue I encountered was with the root component. Take a look at the demo here: https://stackblitz.com/edit/angular-ivy-g2bcty?file=src/index.html

Answer №2

Make sure to include the RouterModule export in your app.module.ts file as well

@NgModule({
declarations: [
  AppComponent,
  ProductList,
  ConvertToSpacesPipe,
  StarComponent,
  ProductDetailComponent,
  WelcomeComponent
],
imports: [
  BrowserModule,
  FormsModule,
  HttpClientModule,
  RouterModule.forRoot([
    {path: 'products', component: ProductListComponent},
    {path: 'products/:id', component: ProductDetailComponent},
    {path: 'welcome', component: WelcomeComponent},
    {path: '', redirectTo: '/welcome', pathMatch: 'full'},
    {path: '**', redirectTo: 'welcome', pathMatch: 'full'}
  ])
],
bootstrap: [AppComponent],
exports: [
  RouterModule,
],
})
export class AppModule { }

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

Discover the data type without using the extends keyword within an interface in Typescript

I'm struggling with making my code declarative enough. I want to infer a type inside an interface scope and then use that same type as an argument for a method within the interface. Here is a simple example: interface Prop { x: infer U, // ^^ ...

Dealing with AOT challenges when integrating ng2-bootstrap into Angular 2 applications

I'm currently developing an Angular 2 app and encountering an error when attempting to create a bundle with AOT compilation following the guidelines in Angular 2 documentation here. The dependency error I'm facing is as follows: Refer to this ...

Why is it that retrieving the same class data from two separate TypeScript files yields varying results in TypeScript? What steps can be taken to resolve this issue

I have created 3 TypeScript files named dataService.ts, init.ts, and interest.ts. The dataService.ts file is a common file used to store and retrieve data from the other 2 files. Within the dataService.ts file: export default class DataService { priv ...

Testing an Angular directive that includes a form unit test

In my directive, I have implemented a form property which is applied to a submit button. The directive listens for click events on the submit button and validates the form when clicked. If the form is not valid, the directive prevents the click event from ...

Unable to import an empty class, encountered error TS2307: Module 'menu' not found

I'm facing an issue where I am trying to import a basic, empty exported class. It seems like the file cannot be located even though it is in the same directory as the class that is importing it. I have looked up similar error messages on Google, but n ...

The JavaScript function for converting a date to a local string in the format of DD MMM YYYY is causing an error message in the browser console stating that it is not a valid function

I am encountering an issue with formatting a date string. The date is currently in the format 2021-03-31T00:00:00, and I need it to be displayed as 31 Mar 2021. In my TypeScript code, I attempted to use the following function: const formattedDate = i.Susp ...

Angular 2 signal sender

I have a specific class definition for my Project: export class Project { $key: string; file: File; name: string; title: string; cat: string; url: string; progress: number; createdAt: Date = new Date(); constructor(file: File) { th ...

The NullInjectorError has occurred due to the absence of a provider for the InjectionToken angularfire2.app

I am currently working on inserting form data into a Cloud Firestore database. Below is my x.component.ts file where I encountered an error in the constructor section: private firestore: AngularFireStore import { Component, OnInit } from '@angula ...

Tips on using checkbox values to filter listing rows in Angular

Question: I have a Filter button with options to filter the listing rows. How can I use this method to filter the values? <button mat-raised-button [matMenuTriggerFor]="filter">Filter</button> <mat-menu #filter="matMenu" yPosition="belo ...

React textarea trigger function on blur event

https://codesandbox.io/s/react-textarea-callback-on-blur-yoh8n?file=/src/App.tsx When working with a textarea in React, I have two main objectives: To remove focus and reset certain states when the user presses "Escape" To trigger a callback function (sa ...

Angular 6 Calendar Template issues with parsing: Unable to link to 'view' as it is not recognized as a valid property of 'div'

I am in the process of developing an application that utilizes this angular calendar. My tech stack includes Angular 6 with AngularFire2 and Firebase. Below is my app.module.ts file: import { BrowserModule } from '@angular/platform-browser'; imp ...

How can I enable email and password login in @auth0/auth0-angular?

Auth0 SDK for Angular Single Page Applications - the documentation outlines two methods for logging in: loginWithPopup loginWithRedirect Is there a possibility to add another option for logging in with just an email and password? ...

Error TS2322: The object with properties "ready: false" and "session: null" cannot be assigned to the type "Readonly<S & withAuthState>"

Here is the interface I'm currently working with: export interface withAuthState { ready: boolean, session: any } Additionally, I have developed the following Higher Order Component (HOC): const withAuth = <P extends withAuthProps, S extends ...

What is the process for including a dependency in an npm package in order to install another npm package?

As I work on creating an npm package for my Angular app, I find myself in need of including a dependency that already exists on npm. My dependency object will include the following entries: "dependencies": { "@angular/animations": "^6.1.0", "@angu ...

What is the best way to set an array as the value for a state variable?

Looking at my function, I have the following situation: execute(e) { let { items } = this.context; let array: number[] = []; for (var i = 0; i < 2; i++) array = [...array, i]; this.setState( { items: array, } ) ...

Error: Angular detected a change in the expression after it was already checked

Being a novice in Angular, I am attempting to construct form validations using code. My requirement is that when I click on the Reset button, the fields should reset. To achieve this, I followed the code below. However, the issue arises when I tap on the ...

What could be causing my Ionic button to not initialize in the expected state while using ngIf with a boolean property connected to an Ionic checkbox?

I'm currently in the process of setting up a list of ingredients with checkboxes and conditional buttons, but I'm facing some challenges with the default state. Ideally, I only want the button to be visible when the checkbox is unchecked so that ...

Tips for updating the display after making an angular $http request using rxjs Observables

I have a project where I am utilizing angular's $http service to fetch data from a remote endpoint. I am keen on incorporating rxjs Observables, hence the call in my service is structured as follows: userInfo() : Rx.Observable<IUserInfo> { ...

How does TypeScript interpret the data type 'a' | 'b' as a string?

As a beginner in TypeScript, React, and English, I apologize for any confusion. I have written a function like this: interface ObjectAttrUniqueState { editVisible: boolean; currentId: number; selectedUnique: number[]; name: string; desc: string; ...

Trying to filter an array of number|undefined in TypeScript to only include numbers is not identified as an array of numbers

Below is the code snippet: type TEntity = Array<{ size?: number }> const someVar: TEntity = //@ts-ignore getFromSomewhere() function isNumber(input: any): input is number { return !isNaN(Number(input)) } const sizes1: number[] = so ...