Looking to implement nested routes in Angular to ensure that each component's view updates properly

app-routing.module.ts

import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
import { BreadcrumbComponent } from './main-layout/breadcrumb/breadcrumb.component';
import { HeaderComponent } from './main-layout/header/header.component';
import { HomeComponent } from './main-layout/home/home.component';
import { SidenavComponent } from './main-layout/sidenav/sidenav.component';
import { AppInfoComponent } from './mobile-cms/app-info/app-info.component';
import { CreateAppComponent } from './mobile-cms/create-app/create-app.component';
import { CreateNewsComponent } from './mobile-cms/create-news/create-news.component';
import { EditAppComponent } from './mobile-cms/edit-app/edit-app.component';
import { EditNewsComponent } from './mobile-cms/edit-news/edit-news.component';

export const APP_ROUTES: Routes = [
  {
    path: '',
    redirectTo: '/home/app-info',
    pathMatch: 'full',
  },
  { path: 'home', redirectTo: '/home/app-info', pathMatch: 'full' },
  {
    path: 'home', component: HomeComponent,
    data: {
      breadcrumb: 'Home'
    },
    children: [
      { path: 'create-app', component: CreateAppComponent,
      data: {
        breadcrumb: 'Create App'
      },
      },
      {
        path: 'app-info', component: AppInfoComponent,
        data: {
          breadcrumb: 'List App'
        },
      },
      {
        path: 'edit-app',
        component: EditAppComponent,

        children: [
          {
            path: 'create-news',
            component: CreateNewsComponent,
            data: {
              breadcrumb: 'Create News'
            }
          },
          {
            path: 'edit-news',
            component: EditNewsComponent,
            data: {
              breadcrumb: 'Edit News'
            }
          },
        ],
        data: {
          breadcrumb: 'Edit App',
        },
      }
    ]
  }
];

@NgModule({
  imports: [RouterModule.forRoot(APP_ROUTES,
    {
      preloadingStrategy: PreloadAllModules,
      useHash: true
  })],
  exports: [RouterModule]
})
export class AppRoutingModule { }

I want to change routes to edit-news and create-news by using router.navigate()

edit-app.component.ts

import { Component, OnInit, AfterViewInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
  selector: 'app-edit-app',
  templateUrl: './edit-app.component.html',
  styleUrls: ['./edit-app.component.scss'],
})
export class EditAppComponent implements OnInit, AfterViewInit {
 constructor(private router: Router){
 }
  ngOnInit(): void {

  }
  ngAfterViewInit(): void {

  }
      editNewsById() {
    this.router.navigate(['home/edit-app/edit-news'])}

      addNews() {
    this.router.navigate(['home/edit-app/create-news'])
  }
}

However, when I click on the Add New button or edit icon, the URL in the address bar gets updated but the view does not update for creating news and editing news while remaining on the edit-app page only.

https://i.sstatic.net/DgpK7.png

Answer №1

When aiming to navigate to child components exclusively, utilizing the relativeTo option can simplify the process.

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

editNewsById() {
    this.router.navigate(['edit-news'], {relativeTo: this.route})}

addNews() {
    this.router.navigate(['create-news'], {relativeTo: this.route })
}

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

How can I link dropdown values to the corresponding property values within a nested array in Angular?

Within my JSON array, there are multiple similar items. Here is an example of one item: { "ownerID": "rkjgAs40NEuSJfp4jquNYQ", "defaultPriceScheduleID": null, "autoForward": false, "id": "44685 ...

Starting a nested JSON structure with TypeScript and Angular 7

I'm encountering an error when attempting to make a POST request by sending an object TypeError: Can not set property 'ItemCode' of undefined My setup involves Angular 7 and Typescript Here is my initial JSON: objEnvio:any = <an ...

Converting base64 dataUrls into images using typescript

When using ng2-image cropper, it does not accept the "src" attribute and instead requires the "image" attribute. As a result, if a dataUrl is provided, the image will not display in the cropper. I am utilizing the camera to capture an image and obtaining ...

Looping through each combination of elements in a Map

I have a Map containing Shape objects with unique IDs assigned as keys. My goal is to loop through every pair of Shapes in the Map, ensuring that each pair is only processed once. While I am aware of options like forEach or for..of for looping, I'm s ...

The datepicker in Angular Material refuses to open when used within a modal dialog box

I successfully integrated an angular material 2 date-picker into a bootstrap modal form: <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">{{title}}</h ...

Encountering a 404 error with Angular 6 routing after refreshing the page when using an Nginx proxy

I currently have my angular application running within a docker container, exposed on port 83. Additionally, I have a separate spring-boot rest app running inside another docker container, exposed on port 8083. On the host server, there is an Nginx server ...

What is the process for inserting a new element into an Array-type Observable?

I've been working on the Angular Tour of Heroes example and I have a feature where users can add new heroes to the existing list. Here's my add hero method in hero.service.ts: addNewHero(hero : Hero) : Observable<Hero> { console.log(her ...

Angular 2/4 - Saving User Object Information in the Front-End Instead of Repeatedly Contacting the Back-End Server

Is there a more efficient way to store and update the current user details in the frontend, without constantly making new HTTP GET requests to the backend every time a new component loads? The solution I came up with is a UserService class that handles se ...

How can a method be called from a sibling component in Angular when it is bound through the <router-outlet>?

In my current project, I have implemented an application that utilizes HTTP calls to retrieve data from an API endpoint and then displays it on the screen. This app serves as a basic ToDo list where users can add items, view all items, delete items, and pe ...

Adjusting the width of an input text field in Angular: A step-by-step guide

What is the best way to adjust the width of an input text in Angular? I recently integrated an input text component called 'njm-input' from a third-party library into my application. However, I encountered difficulties when trying to customize i ...

How can I reload a form page in Angular 9 after making a POST request with HttpClient?

I'm currently working on an Angular 9 application and am facing an issue with refreshing the page after making a POST request using HttpClient. Below is my form and its corresponding component: <form #myForm="ngForm" (ngSubmit)="save(myForm)"> ...

What could be the reason for the webpack:// not showing up in Chrome after running ng build?

Greetings, I'm relatively new to Angular and have noticed a difference between using ng serve and ng build. When I use ng serve, I can see webpack:// in the Chrome debugger which allows me to navigate my TypeScript files for debugging. However, when I ...

How should a string be properly converted to JSON format?

I am encountering an issue with converting the following string to JSON format const banner = " { "banners": [ { "startDate": "02/26/2021", "endDate": "12/25/2021","content": "Important ...

Converting European date format to a standard format

THE ISSUE: The dates retrieved from the API are in European format: 01-06-2018 This means day - month - year (1 June 2018). I want to display these dates in a more visually appealing way - the 'd MMM y' format seems perfect for this purpose ...

"Unlocking the full potential of Typescript and Redux: Streamlining the use of 'connect' without the need to

I am facing some challenges with typescript and redux-thunk actions. The issue arises when my components heavily rely on react-redux connect to bind action creators. The problem occurs when I create the interface for these redux actions within the compone ...

Get the final element with a for loop in Angular 2

I am currently utilizing angular 2 in conjunction with mongoDb. The service I am employing is responsible for calling the API. Here is a snippet of my code: this.at represents a token, similar to fdfdsfdffsdf... This token serves as an authorization key ...

Zod implements asynchronous validation for minimum, maximum, and length constraints

When working with Zod, setting values can be done as shown below: z.string().max(5); z.string().min(5); z.string().length(5); However, in my scenario, the values (e.g., 5) are not predetermined. They are fetched from an API dynamically. How can I create t ...

Tips for resolving TypeScript issues with Vuex mapGetters

When utilizing mapGetters, TypeScript lacks insight into the getters linked to the Vue component, leading to error messages. For instance: import Vue from 'vue'; import { mapActions, mapGetters } from 'vuex'; export default Vue.extend ...

Struggling to use the uploadFiles function with the kendo-upload component

I'm currently facing an issue with uploading my selected files from my component code. I chose the component code route because I need to upload those files after creating the parent aggregate object. This way, I can assign the necessary IDs to my und ...

Eliminate the standard cell padding in nested HTML tables

In my setup, there is a parent table where each td tag in the tr tag contains a child table. Specifically, as shown in the example with Data WS-C3.... in the picture. [![<table class="table table--bordered table--nostripes table-top"> <thead& ...