Angular route fails to load the HTML file

In the process of developing a route within an Angular application, I have successfully implemented 3 routes. However, one particular route is giving me trouble.

I have three folders that need to redirect HTML based on the option chosen. In Angular, I created a folder called "courses" and included the following code:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CoursesDetailComponent } from './courses-detail/courses-detail.component';
import { CoursesComponent } from './courses/courses.component';

const routes: Routes = [
  {path : '', redirectTo: '/courses', pathMatch: 'full'},
  {path : 'courses', component: CoursesComponent},
  {path : "/courses/:id", component: CoursesDetailComponent}
]

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

All paths work perfectly except for the last one - when saved in the code, the browser displays nothing.

The code pertaining to information about courses is as follows:

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

@Component({
  selector: 'app-courses',
  templateUrl: './courses.component.html',
  styleUrls: ['./courses.component.css']
})
export class CoursesComponent implements OnInit {
  
  courses = [
    {'id': 1, 'name': 'Angular'},
    {'id': 2, 'name': 'React'},
    {'id': 3, 'name': 'MongoDB'},
    {'id': 4, 'name': 'Ruby'},
    {'id': 5, 'name': 'Bootstrap'},
  ];

  constructor(private router: Router,
              private route: ActivatedRoute) { }


  ngOnInit(): void {
  }

  onSelect(courses: any){
    this.router.navigate(['/courses', courses.id]);
  }

}

I cannot figure out the issue - when adding the following line, the code compiles but nothing appears in the browser:

{path : "/courses/:id", component: CoursesDetailComponent}

Answer №1

If you are working on the AppRoutingModule, make sure to eliminate the initial / in the path attribute. It should be modified as shown below:

{path : "courses/:id", component: CoursesDetailComponent}

Furthermore, ensure that you do the same in your onSelect() function. The updated version should resemble the following snippet:

onSelect(courses: any){
    this.router.navigate(['courses', courses.id]);
}

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

Having trouble implementing object type switching in Typescript

While in the process of developing an angular application, I stumbled upon a peculiar issue. Some time ago, I crafted this piece of code which performed flawlessly: selectedGeoArea: any receiveStoreEvent(event) { switch (event.constructor) { ca ...

Can I include `ChangeDetectorRef` in an Angular 4 service constructor?

In my service file, I have a system that alerts about Subjects. The value is set and then reset to null after 3 seconds using the setTimeout() method. However, upon adding changeDetection: ChangeDetectionStrategy.OnPush to the app.component.ts, it appears ...

What is the reason for the ngFor loop in Ionic 5 component not functioning properly?

I'm facing an issue with the *ngFor directive in one of my components. It's strange because it works fine in other components. Can anyone help me figure out what I might be doing wrong? @Component({ selector: 'app-age-picker', temp ...

angular component that takes a parameter with a function

Is there a way for my angular2 component to accept a function as a parameter? Uncaught Error: Template parse errors: Can't bind to 'click' since it isn't a known property of 'input'. (" minlength="{{minlength}}" [ERROR -&g ...

What is the best way to merge import all with different elements?

My TSLint is flagging the following issue: Multiple imports from 'moment' can be combined into one. Here is the code causing the problem: import * as moment from 'moment'; import { Moment } from 'moment'; I have attempted ...

Having trouble with Angular 4 data display? See how to fix a simple example that's

I can't seem to display my data correctly in Angular. When I try, all I get are empty bullet points and an error message that says "Cannot read property of 0 undefined." Even though the code appears to be correct, it's not functioning as expected ...

Determine whether or not there are any duplicate elements within an array object

Is there a way to determine true or false if there are any duplicates within an object array? arr = [ { nr:10, name: 'aba' }, { nr:11, name: 'cba' }, { nr:10, name: 'aba' } ] arr2 = [ { year:2020, cit ...

How to verify if an unknown-type variable in TypeScript contains a specific property

When using typescript with relay, the props passed down are of type unknown. Despite my efforts, I am unable to persuade the compiler that it can have some properties without encountering an error: <QueryRenderer environment={environment} query={te ...

Guarding Routes and Navigating Dynamically in Angular

My application features a dynamic navigation bar that changes based on the user's access level within different areas of the product. Utilizing Angulars Route Guards ensures that users can only access routes they have permission for, which has been wo ...

Exploring the functionalities of arrays in Typescript: A beginner's guide

Currently, I am working on a react project and building a store within it. Below is the code snippet I have implemented: import React, { useReducer, useEffect } from 'react'; import { v4 as uuid } from 'uuid'; import { Movie, MoviesAct ...

Transition Angular 2 Release Candidate to production environment

As we continue working on our web application using Angular 2 RC, I am curious about the feasibility of upgrading to the final version of Angular once it is released. Is it possible to seamlessly upgrade the Angular JS Framework in our production environ ...

Restricting the selection of only one checkbox in an Ionic4 application

Currently working on enabling only one checkbox in my Ionic 4 app. I've made some progress with the code but now I'm stuck. I believe I need to implement ngModel for this task. The goal is to set response.checked to true when a checkbox is checke ...

Is there a way to retrieve the value of an option passed by serverless CLI in serverless.ts file?

As I explored the serverless framework with serverless.ts for configuration, a certain question came to mind. When utilizing the serverless CLI, passing values can be done in the following way: serverless offline --stage prod In the serverless.yml file, ...

Using Angular 2: Exploring the power of observables for broadcasting events during a forEach loop

Upon testing the service within a forEach loop, I noticed that the parameter I passed to the service ended up being the last one in the iteration. I initially suspected that the issue was due to closures, so I attempted using an anonymous function to add ...

The issue with making an HTTP POST request in Angular 2

Service: postJson() { var json = JSON.stringify({ "key": "CT", "values": ["FSP", "HMC", "PHYP","hell"] }); let headers = new Headers({'Content-Type':'application/json'}); //let options = new RequestOptions({ ...

Connect store variables to components using Angular's ngrx

I am attempting to link the location variable in my component to another variable in the store using a selector with ngrx v13 in Angular. However, when I include the variable with the property in the HTML, I encounter an error: Error message: Property &ap ...

Tips on sending component values to Host Listener in Custom Directives using Angular 2

I am looking to transmit model values from my HTML template to a custom directive: @Directive({ selector: '[eventlistener]' }) export class EventListener { @Input() value:string = 'Not Defined'; @HostListener('click& ...

A guide on implementing the intl-tel-input plugin within an Angular 2+ project

Component : ng2-tel-input, Framework : Angular 4, JavaScript library : intl-tel-input Upon completing the installation with npm i ng2-tel-input I stumbled upon a note in the node_modules\intl-tel-input\src\js\intlTelInput.js file that ...

Dynamically divide canvas screens based on fabricjs dropdown selection

I am attempting to implement split screens in fabric js, such as 1, 2, 4, 8, and 16. The screen should split based on the selection from the dropdown menu. Check out my current code where I have successfully uploaded images. If I click on the images, th ...

ng serve: Module 'tapable' not found

After moving my Angular 5 project to a new computer, I encountered an issue when attempting to ng serve: Cannot find module 'tapable' Error: Cannot find module 'tapable' at Function.Module._resolveFilename (module.js:469:15) at ...