Tips on passing an object as data through Angular router navigation:

I currently have a similar route set up:

this.router.navigate(["/menu/extra-hour/extra-hours/observations/", id])

The navigation is working fine, but I would like to pass the entire data object to the screen in order to render it using the route. How can I achieve this?

What would be the most effective approach to accomplish this task?

Answer №1

It is recommended not to pass data objects through routes, but rather utilize a common service or BehaviorSubject(rxjs) for such purposes.

If you still wish to pass data through routes, here is how you can do it:

In the current component, set the data to the route as shown below

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

@Component({
  selector: 'app-form1',
  templateUrl: './form1.component.html',
  styleUrls: ['./form1.component.css']
})
export class Form1Component {
  
  constructor(private router: Router) {

  }

  handleButtonClick() {
    const myObject = { name: 'John', age: 30 };

    const navigationExtras: NavigationExtras = {
      state: {
        data: myObject
      }
    };

    this.router.navigate(['/list'], navigationExtras);
  }
}

Next, access the data in the target component within the ngOnInit method

ngOnInit() {
    const currentState = this.router.lastSuccessfulNavigation;
    console.log(currentState?.extras)

  }

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

Guide on dividing a URL string in Angular framework

Is there a way to include a value directly in the URL, like so: http://example.com/component/july2021 I need to extract july2021 from the component and separate it into "july" and "2021". How can I achieve this? ...

Filtering based on the boolean value of a checkbox in Angular

I'm struggling to implement a boolean filter for my search results, separating users with financial debt from those without. I need some guidance on how to achieve this. Data Filter @Pipe({ name: 'filter' }) export class FilterPipe implem ...

Schedule - the information list is not visible on the calendar

I am trying to create a timeline that loads all data and events from a datasource. I have been using a dev extreme component for this purpose, but unfortunately, the events are not displaying on the calendar. Can anyone offer any insights into what I might ...

Is it possible to eliminate additional properties from an object using "as" in Typescript?

I am looking for a way to send an object through JSON that implements an interface, but also contains additional properties that I do not want to include. How can I filter out everything except the interface properties so that only a pure object is sent? ...

Implementing Routes in Express Using Typescript Classes

Seeking assistance in converting a Node.js project that utilizes Express.js. The objective is to achieve something similar to the setup in the App.ts file. In pure Javascript, the solution remains unchanged, except that instead of a class, it involves a mo ...

Leverage the child interface as a property interface containing a generic interface

I'm facing an issue while trying to incorporate typings in React. The concept is centered around having an enum (EBreakpoint) that correlates with each device we support. A proxy wrapper component accepts each device as a prop, and then processes the ...

Missing value in Angular HTML template

Upon reviewing my input, an error has been detected: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'true'. Current value: 'null'. This specific line is the root cause of the i ...

Tips for testing the window.innerWidth property in Angular 8?

I am relatively new to Angular and TDD. Right now, I am attempting to test a function that is called during a resize event. Below is the code snippet in question: header.component.ts @Component({ selector: 'app-header', templateUrl: &ap ...

What is the best way to separate a string using a comma as a delimiter and transform it into a string that resembles an array with individual string elements

I am in search of a way to transform a string, such as: "one, two, three, four" into a string like: "["one", "two", "three", "four"]" I have been attempting to devise a solution that addresses most scenarios, but so far, I have not been successful. The ap ...

pick only one option from each row

I am working on a feature where I have five rows with two checkboxes each generated using a loop and property binding. Currently, clicking on one checkbox selects all elements in the column. However, I want to achieve selection row-wise. Is there a method ...

Angular and Spring Boot integration with Apereo CAS application

For my current project, I am building an application with Angular6 for the frontend and spring boot for the backend. Initially, all APIs in my backend are open to everyone, accessible via URLs like localhost:8080/api/get_data from the frontend. However, I ...

Is the detection change triggered when default TS/JS Data types methods are called within an HTML template?

I'm currently updating an application where developers originally included function calls directly in the HTML templating, like this: <span>{{'getX()'}}</span> This resulted in the getX method being called after each change dete ...

Angular, Transforming JSON with RxJS Operators in TypeScript

Upon receiving the JSON object (Survey) from the server, it looked like this: { "id": 870, "title": "test survey", "questions": [ { "id": 871, "data": ...

Ways to retrieve form data from a dynamic CDKPortalComponent

I have a dynamic cdkportal component that is created from a variety of Components. These components are added to a modal dialog, and I need to determine the validity of the forms within them. If any of the child component forms are invalid, I want to disab ...

Ways to troubleshoot issues with the ng bootstrap package

Having an issue debugging ng-bootstrap 4 in my Angular 7 project, I decided to follow the instructions provided on this link to clone ng-bootstrap and install dependencies using yarn. The process completed without any errors. However, when attempting to np ...

Guide on how to include jquery-ui css file in Vue3

I am new to TypeScript and VueJs. Recently, I decided to incorporate jquery-ui into my project using Vue3, TypeScript, and Electron. After some trial and error, I was able to successfully set up the environment. However, when I attempted to use the jquery ...

Exploring Angular's search functionalities using reactive forms

Hey there! I'm in need of some assistance. I'm currently attempting to perform a live search for elements that are both alive and responsive to case sensitivity when searching. My array, called elementsArray, contains fields such as: id, name, an ...

Is there a mistake in the TypeScript guide for custom typography in MUI5?

Currently, I am in the process of setting up custom typography variants in MUI5 by referencing this helpful guide: https://mui.com/customization/typography/#adding-amp-disabling-variants. As I follow step 2 and input the type definitions: declare module &a ...

Prevent automatic suggestions from appearing in Ionic app on Android

Our Ionic v4 (Angular, Cordova) app features form input fields (<ion-input>) like the example below: <ion-input formControlName="firstName" type="text" inputmode="text" autocapitalize="sentences"></ion-input> When running the Android ap ...

Every time I try to use AgGrid selectors, they consistently come back with null results, even though the

I currently have an ag grid in my application: <app-my-component> <ag-grid-angular [gridOptions]="gridOptions" (gridReady)="setGridReady()"> </ag-grid-angular> </app-my-component> When running Karma- ...