Angular's queryParams do not appear to properly connect with the query parameters

My code seems to have a mistake somewhere, but I can't figure it out. In my

[queryParams] = "{allowEdit: server.id == 3 ? 1 : 0}"
, the params object is empty when I subscribe to it in the edit-server component. Why is it empty and how do I add allowEdit to it? Maybe the issue lies in an incorrect path? Let me provide more details about relevant paths.

Here is the code snippet:

ServerS Template

  
      <a
        [routerLink] = "['/servers', server.id]"
        [queryParams] = "{allowEdit: server.id == 3 ? 1 : 0}"
        href="#"
        class="list-group-item"
        *ngFor="let server of servers">
        {{ server.name }}
      </a>
    <router-outlet></router-outlet>

Server Template:

<h5>{{ server.name }}</h5>
<p>Server status is {{ server.status }}</p>
<button class="btn btn-primary" (click)="onEdit()">Edit Server</button>

Server TS:

export class ServerComponent implements OnInit {
  server: {id: number, name: string, status: string};
  id: number

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

  ngOnInit() {
    this.id = +this.route.snapshot.params['id']
    this.server = this.serversService.getServer(this.id)
  
    this.route.params.subscribe((params: Params) => {
      this.server = this.serversService.getServer(this.id)

    })

  }

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

}

Edit Server TS:

export class EditServerComponent implements OnInit {
  server: {id: number, name: string, status: string};
  serverName = '';
  serverStatus = '';
  allowEdit: boolean

  constructor(private serversService: ServersService, private route: ActivatedRoute) { }
  ngOnInit() {
    this.route.snapshot.queryParams
    this.route.snapshot.fragment
    this.route.queryParams.subscribe((params: Params) => {
      console.log(params['allowEdit']) // for some reason, params['allowEdit'] gives us undefined
      this.allowEdit = params['allowEdit'] == 1 ? true : false
    })
    this.route.fragment.subscribe((params: string) => {
    
    })
    //
    this.server = this.serversService.getServer(1);
    this.serverName = this.server.name;
    this.serverStatus = this.server.status;
  }
}

Please note that some code blocks may be irrelevant, but if you need more information, feel free to ask. Here's my folder structure and AppModule paths for reference.

App Module:

const appRoutes: Routes = [
  {
    path: 'users',
    component: UsersComponent,
    children: [ {
      path: 'users/:id/:name',
      component: UserComponent
    }]
  },
  {
    path: '',
    component: HomeComponent
  },

  // The ones below are the important ones
  {
    path: 'servers',
    component: ServersComponent,
    children: [  {
      path: ':id/edit',
      component: EditServerComponent
    },
    {
      path: ':id',
      component: ServerComponent
    }]
  },
  
]

Relevant Folder Structure

Answer №1

You've hit the nail on the head: the allowEdit parameter is only sent to the route servers/:id

If you wish to retrieve it from the servers/:id/edit component, you must define it as a child of the servers/:id route:

const appRoutes: Routes = [
  // other routes
  {
    path: 'servers',
    component: ServersComponent,
    children: [
      {
        path: ':id',
        component: ServerComponent,
        children: [
          {
            path: 'edit',
            component: EditServerComponent
          },
        ]
      }
    ]
  },
]

In the EditServerComponent, you'll need to access the data through the parent route:

this.route.parent.queryParams.subscribe(...)

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

Following the update to Angular 6, an error was encountered: CssSyntaxError:

Currently, I am in the process of upgrading my Angular 5 application to Angular 6. Following all the necessary steps outlined on update.angular.io, I have encountered a compilation error that persists even after completion of the upgrade process. The err ...

Step-by-step guide on incorporating an external library into Microsoft's Power BI developer tools and exporting it in PBIVIZ format

I'm attempting to create a unique visualization in PowerBI using pykcharts.js, but I'm running into issues importing my pykcharts.js file into the developer tool's console. I've tried including a CDN path like this: /// <reference p ...

The fix for the unresponsive fixed container in Angular 2 Material

I've encountered an issue with CSS and Angular 2 material. Any element with a fixed position doesn't behave as expected inside an md-sidenav-container. However, when it is placed outside the container, it works perfectly. I have created a Plunker ...

Error in Typescript stating that the property 'children' is not found on the imported interface of type 'IntrinsicAttributes & Props'

When I try to import an interface into my Card component and extend CardProps, a yarn build (Typescript 4.5.4) displays the following error: Type error: Type '{ children: Element[]; className: string; border: true; disabled: boolean; }' is not as ...

`How can I sort information based on a chosen parameter?`

Is it possible to combine the two conditions into one within the function onSelectedReport()? Representing these conditions in HTML would result in: HTML: <div *ngFor="let report of reports"> <div *ngFor="let i of income"> <di ...

The error TS2339 is indicating that there is no property called myProperty on the type SetStateAction<User>

I'm encountering a TypeScript error while working with React that's leaving me puzzled: <html>TS2339: Property 'subEnd' does not exist on type 'SetStateAction&lt;User&gt;'.<br/>Property 'subEnd' d ...

What could be the reason for typescript not issuing a warning regarding the return type in this specific function?

For instance, there is an onClick event handler attached to a <div> element. The handler function is supposed to return a value of type React.MouseEventHandler<HTMLDivElement> | undefined. Surprisingly, even if I return a boolean value of fal ...

Struggling with TypeScript errors due to React.HTMLProps for HTMLAnchorElement

When trying to extend a React component with React.HTMLProps without explicitly defining onClick in the attribute list, ESLint complains when passing onClick as an attribute while using the component. Here's an example of the code: The React componen ...

Using React-Router-Native to send an image as a parameter

I am encountering an issue while attempting to pass an image as a parameter in react-router-native and retrieve the data from location.state. Typically, I use the following code to display an image: import Icon from '../image/icon.png'; <Vie ...

Access User Authentication Profile Information in Firebase Utilizing Angular 2

Need assistance with retrieving user profile information from Angularfire Authentication in Angular? Specifically looking to access the user's Facebook profile picture and name. Your help would be greatly appreciated. Thank you! I have attempted the ...

Unable to find custom components when using react-router

My goal is to improve the organization of my Routes in React and separate concerns. I am currently utilizing react-router-dom version 5. Within my Application Routes component, I have structured it with 3 children components: AuthenticatedRoutes PublicRo ...

Error encountered when implementing Angular Model Class within an array structure

In the current project, I have developed a class and am attempting to utilize the constructor format for certain content within the project. Here is my Angular class - import { Languages } from './temp-languages.enum'; export class Snippet { ...

What method is the easiest for incorporating vue.js typings into a preexisting TypeScript file?

I currently have a functional ASP.NET website where I'm utilizing Typescript and everything is running smoothly. If I decide to incorporate jQuery, all it takes is running npm install @types/jQuery, and suddenly I have access to jQuery in my .ts file ...

Merge two arrays by matching their corresponding identifiers

I have 2 separate arrays that I need to merge. The first array looks like this: const Dogs[] = [ { id: '1', name: 'Buddy' }, { id: '2', name: 'Max' }, ] The second one: const dogAges[] = [ { id: '4&ap ...

Displaying nested web service array data in Angular 4

I created a project that retrieves data from a web service API. However, the API contains nested arrays that also need to be displayed. How can I access the data from these nested JSON arrays? What is the correct way to extract this data within the HTML co ...

I am unable to run ng serve at the moment

Every time I enter ng serve it shows: Your global Angular CLI version (10.0.1) is higher than your local version (6.2.9). The local Angular CLI version will be used. To prevent this warning, use ng config -g cli.warnings.versionMismatch false. Schema va ...

Why is Axios not being successfully registered as a global variable in this particular Vue application?

Recently, I have been delving into building a Single Page Application using Vue 3, TypeScript, and tapping into The Movie Database (TMDB) API. One of the hurdles I faced was managing Axios instances across multiple components. Initially, I imported Axios ...

Employing the ngFor directive, insert two elements onto a single row, then proceed to generate a fresh

For some time now, I've been attempting to loop through an array of objects using *ngFor and place two elements inside each row. The goal is to generate a new row after every two components have been added. Here's what I've attempted so far ...

What situations call for the use of 'import * as' in TypeScript?

Attempting to construct a cognitive framework for understanding the functionality of import * as Blah. Take, for instance: import * as StackTrace from 'stacktrace-js'; How does this operation function and in what scenarios should we utilize imp ...

Troubleshooting issue with React and Material UI Table pagination display

Issue with Material UI Table Display When Changing Pages When receiving an array of Artist Objects through props to create a checklist table, I encounter some display issues. The table works fine initially, but when changing pages or sorting, more rows th ...