Showing nested routes component information - Angular

I am working on a project that includes the following components:

TodosComponent (path: './todos/'): displaying <p>TODO WORKS</p>

AddTodosComponent (path: './todos/add'): showing

<p>ADD TODO WORKS</p>

DeleteTodosComponent (path: './todos/delete'): presenting

<p>DELETE TODO WORKS</p>

Both Add and Delete are nested routes within Todos.

In my main AppComponent, I have a side navigation with links for all 3 components (TodosComponent, AddTodosComponent, DeleteTodosComponent).

The issue arises when attempting to display the contents of the clicked component in the content area of AppComponent. On clicking child routes, an error is triggered: "Cannot match any routes. URL Segment: 'todos/add'"

How can I ensure that clicking a link in the sidenav displays the corresponding HTML content from the component?

app-routing.module.ts

const appRoutes: Routes = [
  { path: '', redirectTo: '/todos', pathMatch: 'full' },
  { path: 'todos', component: TodosComponent, pathMatch: 'full', children: [
    { path: 'add', component: AddTodoComponent},
    { path: 'delete', component: DeleteTodoComponent},
  ]},
]

@NgModule({
  imports: [RouterModule.forRoot(appRoutes)],
  exports: [RouterModule]
})

app.component.html

<mat-sidenav-container>
  <mat-sidenav opened="true" mode="side" fixedInViewport="true">
    <p>I am the sidenav</p>
    <mat-nav-list>
      <mat-list-item>
        <a matLine routerLink="/todos">List Todos</a>
      </mat-list-item>
      <mat-list-item>
        <a matLine routerLink="/todos/add">Add Todo</a>
      </mat-list-item>
      <mat-list-item>
        <a matLine routerLink="/todos/delete">Delete Todo</a>
      </mat-list-item>
    </mat-nav-list>
  </mat-sidenav>
  <mat-sidenav-content>
    <router-outlet></router-outlet>
    <p>Main Content</p>
  </mat-sidenav-content>
</mat-sidenav-container>

My goal is to achieve something similar to this: https://i.sstatic.net/QgvSd.jpg

Answer №1

This is an excerpt taken from the official Angular documentation.

When pathMatch = 'full' is specified, a route will be matched only if all remaining segments of the URL match ''.

For instance, consider the path todos. The unmatched portion after this path is /todos/add, which does not meet the exact criteria for a match. Therefore, the router will skip the children components and proceed to the next defined path (if any). If no suitable match is found, you'll encounter the error message you've encountered :)

To resolve this issue, simply remove pathMatch: 'full' from the /todos path in your code:

const appRoutes: Routes = [
  { path: '', redirectTo: '/todos', pathMatch: 'full' },
  { path: 'todos', component: TodosComponent,  children: [
    { path: 'add', component: AddTodoComponent},
    { path: 'delete', component: DeleteTodoComponent},
  ]},
]

Answer №2

Exploring the importance of having different sections within the same router-outlet.

const appRoutes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: '/home', component: HomeComponent }, 
  { path: '/products', component: ProductsComponent },
  { path: '/cart', component: CartComponent }
]

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

Why aren't special methods/mixins for Sequelize associations being generated?

According to the documentation available at https://sequelize.org/docs/v6/core-concepts/assocs/#special-methodsmixins-added-to-instances: When establishing an association between two models, special methods are introduced that enable instances of those mo ...

What could be causing the abortTransaction() method in mongoose to not function as

System OS: MacOS 10.15.5 NodeJS Version: 10.16.3 Mongoose Versions: 5.8, 5.9 MongoDB Version: 4.0.3 The following code snippet is in question: import User from 'models/user' const session = await User.startSession() session.startTransaction() ...

What is the best way to utilize the outcome of the initial API request when making a second API call in AngularJS

Looking to utilize the response of a first API call in a second API call. The situation is such that I need to fetch data from the first API and use it in the second API call. I believe a synchronous API call would be necessary. While attempting to imple ...

What is a method for saving a file from Chrome to a network drive using scripting language, even though it's currently functioning in IE?

In a SharePoint 2013 document library, I have implemented a JavaScript function that captures user access to files. The function creates a .txt file containing information about the user ID, username, and file path, which is then saved to a network drive l ...

Saving resources with a promise in Angular

I am facing a challenge while trying to handle a promise from the angular $resource save function. According to the documentation, I should be able to access the raw $http promise by using the $promise property on the returned object. Here is an example: ...

Ways to streamline redundant code by creating a higher order function that accepts different parameter types in TypeScript

Recently, I've been exploring the idea of refactoring this code into a higher order function using TypeScript to enhance its cleanliness and reusability. However, I'm facing quite a challenge in getting it to work seamlessly. import { DocumentDef ...

Exploring AngularJS: The Innovative Navigation Bar

My goal is to incorporate the functionality demonstrated in this example: https://material.angularjs.org/1.1.1/demo/navBar To achieve this, I have created the following index.html: <!DOCTYPE html> <html lang="en"> <head> &l ...

Using Bootstrap 5 to display a modal using JavaScript

Creating a sleek gallery using bootstrap 5, and curious about how to activate a bootstrap modal without including "data-bs-..." in the HTML (to prevent repeating those data- attributes multiple times). I have successfully written a functioning JavaScript ...

Filtering Arrays of Objects: A Guide to Filtering in JavaScript

Could really use some assistance with sorting an array of objects in javascript. My users array looks like this: var users = [ { first: 'Jon', last: 'Snow', email: '<a href="/cdn-cgi/l/email-protection" class="__ ...

Encountering the issue of receiving undefined values for both error and url during the utilization

I'm currently working on a file called createCheckoutSession.ts: import { db } from '../firebase/firebaseInit'; import { collection, addDoc, onSnapshot } from 'firebase/firestore'; import { User } from 'firebase/auth'; e ...

Expanding Headers with JavaScript

Looking to add a Stretchy Header Functionality similar to the one shown in this GIF: Currently, on iPhones WebView, my approach involves calling a Scope Function On Scroll (especially focusing on Rubberband Scrolling) and adjusting the Image Height with C ...

What is the best way to generate dynamic components on the fly in ReactJS?

Could you please guide me on: Techniques to dynamically create react components, such as from simple objects? Is it possible to implement dynamic creation in JSX as well? Does react provide a method to retrieve a component after its creation, maybe b ...

What is the best way to handle JSONp response parsing using JavaScript?

I'm relatively new to working with Javascript and I am currently attempting to retrieve data from an External API located on a different website. My goal is to extract the information, parse it, and then display specific parts of it within my HTML pag ...

Track the cursor's movement

Looking to add an animation effect to my website. I want the navbar to follow the cursor within a limited space when hovered over. Check out this example for reference: . Here's the code I have so far, but it's not quite achieving the desired res ...

Close the Bootstrap Modal by clicking the back button within SweetAlert

**How can I close a Bootstrap modal when clicking the back button in SweetAlert? I have tried using modal.hide() but it's not working. I am using Bootstrap version 5 and even checked their documentation with no luck. Does anyone know how to achieve th ...

Enhance the functionality of AngularJS (Restangular) by encapsulating service methods with a

Initially, when using basic $http, I had this code snippet in a service: var fetchSomeData = function() { var deferred = $q.defer(); $timeout(function() { $http.get('...mylongurl', { headers: { 'Content-Type& ...

What steps can be taken to resolve the Angular error stating that the property 'bankCode' is not found on type 'User' while attempting to bind it to ng model?

I'm encountering an issue with my application involving fetching values from MongoDB and displaying them in an Angular table. I've created a user class with properties like name and password, but I keep getting errors saying that the property doe ...

Deciphering the Results of AngularJS

What sets 'template' apart from 'templateUrl' in AngularJS directive? index.html: <!DOCTYPE html> <html lang="en" ng-app="app"> <head> <meta charset="utf-8"> <title>Index</title> </he ...

Utilizing the js-yaml library to parse a YAML document

Currently, I'm utilizing js-yaml to analyze and extract the data from a yaml file in node js. The yaml file consists of key-value pairs, with some keys having values formatted like this: key : {{ val1 }} {{ val2 }} However, the parsing process enco ...

What is the process for displaying HTML page code received from an AJAX response?

My current project involves implementing JavaScript authentication, and I have a specific requirement where I need to open an HTML file once the user successfully logs in. The process involves sending an AJAX request with the user's username and passw ...