What is the best way to transfer information between two components when working with an edit form?

Presently, I am utilizing a modal material dialog window that prompts the user to input a number and then press search. Upon searching, it retrieves data from an API call and receives a response object. My goal is to utilize this response object to populate a new page (edit form).

My inquiry is, how can I transfer the data, specifically the number entered by the user on the material dialog component, to another component so that it can retrieve the API call results? Or how can I transmit my response object to my edit form from the dialog?

For example:

This is my search function:

search(searchNumber) {
    if (this.selectedOption === 'Bill Number') {
      this._transactionService.findExistingTransactionByBillNumber('U001', searchNumber)
                               .subscribe(data => this.transactionResponse = data);
      console.log(JSON.stringify(this.transactionResponse));

      this.router.navigate(['/edit-transaction-portal']);

    } else {
      this._transactionService.findExistingTransactionByTransactionNumber('U001', searchNumber)
                               .subscribe(data => this.transactionResponse = data);
             console.log(JSON.stringify(this.transactionResponse));
             this.router.navigate(['/edit-transaction-portal']);
      }
    }

I would like to either 1) send the response object obtained here or send the searchNumber entered by the user, so that I can perform a lookup within my edit form component. I need to pass either one from this component to the new component that I navigate to.

EDIT: The accepted solution demonstrates how to add query params to this.router.navigate() and how to retrieve it by subscribing to activateRoute, a different approach than the one identified in the other SO post.

Answer №1

If you need to retrieve the number (bill/transaction)

this.router.navigate(['/edit-transaction-portal'], { queryParams: { bill: 'U001' } });
this.router.navigate(['/edit-transaction-portal'], { queryParams: { transaction: 'U001' } });

then within your

component(edit-transaction-portal)
, make an API call to fetch the required data. Make sure to have ActivatedRoute included in the constructor like so:

isBill: boolean;
isTransaction: boolean;
number: string;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
    this.sub = this.route
      .queryParams
      .subscribe(params => {
        this.isBill = params['bill'] != undefined;
        this.isTransaction = params['transaction'] != undefined;
        this.number = this.isBill ? params['bill'] : params['transaction'];
        // Perform API request here
      });
}

Answer №2

My question is how I can transfer the information, specifically the number entered by the user on the material dialog component, to another component.

You can transmit it through the material dialog component. Include dialogRef in your component that was opened in the dialog:

constructor(
   public dialogRef: MatDialogRef<SomeComponent>,   
   @Inject(MAT_DIALOG_DATA) public data: any,    
  ) { }

Upon submitting the data, you can pass any data to the component that opened this dialog by closing the dialog:

  onSubmit() {
    this.service.postProduct(this.contract, this.product)
      .subscribe(resp => {
        this.dialogRef.close(resp);
      });

  }

In your parent component, which initiated the opening of this dialog, you can retrieve this passed data by subscribing to the afterClosed() observable:

Parent.component.ts:

openDialog(id) {
    const dialogRef = this.dialog.open(SomeComponent, {

      data: { id: anyData}
    });
    dialogRef.afterClosed().subscribe(result => {
      if (result) {
         // do something...
      }
    });
  }

If I pass the data object in dialog.open(), how do I retrieve it from there?

Refer to the openDialog() function above. It includes a data property that can be sent to dialog components. In the opened component, inject MAT_DIALOG_DATA as follows:

@Inject(MAT_DIALOG_DATA) public data: any, 

This will allow you to access the passed data object as demonstrated in the code snippet above.

Official docs[sharing-data-with-the-dialog-component]

Answer №3

In order to transfer data via routing, you need to specify a route that includes the value as part of the route definition like shown below:

const appRoutes: Routes = [
  { path: 'hero/:id',      component: HeroDetailComponent },
];

This is how it will work on the code side:

gotoHeroes(hero: Hero) {
  let heroId = hero ? hero.id : null;
  // Pass along the hero id if available
  // so that the HeroList component can select that hero.
  // Include a junk 'foo' property for fun.
  this.router.navigate(['/heroes', { id: heroId, foo: 'foo' }]);
}

Reference: https://angular.io/guide/router#router-imports


When you need to pass data between two components, Angular provides the concepts of @Input and @Output properties which facilitate data transfer between components.

@Input() - Allows passing data from parent to child component.

@Output() - Enables passing data from child to parent component.


An alternative method is by utilizing a Service to share the same instance of the service among components.

Further reading: 3 ways to communicate between Angular components

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

Retrieve the input field value using JavaScript within a PHP iteration loop

I've implemented an input box inside a while loop to display items from the database as IDs like 001,002,003,004,005 and so on. Each input box is accompanied by a button beneath it. My Desired Outcome 1) Upon clicking a button, I expect JavaScript t ...

The highlighted red lines in Visual Studio Code

I am facing an issue with some red squiggles in my code: https://i.sstatic.net/UBmgi.jpg To address this, I have declared variables like this: import SearchFilterViewModel = SearchFilter.SearchFilterViewModel; import SearchResultsViewModel = SearchResul ...

Forcing a property binding update in Angular 2

Take a look at this particular component import {Component} from 'angular2/core' @Component({ selector: 'my-app', providers: [], template: ` <div> <h3>Input with two decimals</h3> <input type ...

Creating a signature for a function that can accept multiple parameter types in TypeScript

I am facing a dilemma with the following code snippet: const func1 = (state: Interface1){ //some code } const func2 = (state: Interface2){ //some other code } const func3: (state: Interface1|Interface2){ //some other code } However, ...

Having trouble altering the error response code in feathers.js

I'm utilizing an authentication service for login validation. In this case, I am looking to change the Unauthorized (401) response code to 200 while keeping the message the same. The authentication service setup is as follows: app.service('auth ...

Exploring the possibilities of developing WebComponents within Angular using TypeScript

My Angular application was originally created using the default method with ng new project-name". However, for performance reasons, I had to incorporate single standard WebComponents. The JavaScript code associated with these components is stored in a ...

The MatInput value will only display after the page is reloaded or refreshed

After refreshing the page, a matInput field displays a value or result that was previously hidden. https://i.stack.imgur.com/q9LQI.png By selecting or highlighting within the matInput, the value or result becomes visible. https://i.stack.imgur.com/SqaLA.p ...

extracting a JSON array from an API

I'm trying to extract the title from my API using JavaScript and then display it in HTML. api:(https://k0wa1un85b.execute-api.us-east-1.amazonaws.com/production/books) The JSON response is as follows: {"statusCode":200,"body":[{"id":"4f160b1f8693cd ...

How do I utilize JSON to transmit a string to my server with Tornado?

Currently, I am facing an issue with my HTML input box and a JavaScript function that is triggered upon clicking a submit button. My goal is to send the data entered by the user in the input box to my Tornado server. Despite trying various options, I have ...

Disregard any labels when it comes to clickable areas for mouse events

Here is a simple example in JSFiddle where a text is displayed over an image inside a div element. Depending on where the cursor hovers, it can exhibit three different behaviors: pointing hand over the image, allowing text selection over the content of the ...

Difficulty adding extra arguments to a function

I am currently working on a function in d3 that aims to evaluate the "time" of my data and determine if it falls within specific time intervals. This will then allow me to filter the data accordingly. //begin with a function that checks if the time for eac ...

Leveraging event listeners in conjunction with React's useEffect function

Check out the code example on Code Sandbox here Hey there, I'm trying to implement a feature where clicking a button inside a container displays a box. I've set up an event listener so that when you move your mouse outside the container, the box ...

How can I stop the li item from swiping right in JQuery mobile?

I've been implementing this code from https://github.com/ksloan/jquery-mobile-swipe-list and I've made some modifications to it. It's been working well for me so far. However, the code includes two buttons - one on the right and one on the l ...

Ways to prevent scrolling or switching to the next tab when my javascript function yields a false result

//HTML Code <div id="navigation1"> <ul> <li><a href="#"><input type="submit" value="Next" onClick="return checkfhname()" /></a></li> </ul> </div> Whenever my Javascript function checkfhname() r ...

nodejs callbacks and their return values

Hey guys, I'm having trouble resolving an issue with a JavaScript callback return. Here's the function in question: //Function to get user's contact list function get_contact_list(data) { //Retrieve user ID based on ...

Avoid Sequelize automatically appending 'Id' to column names caused by association configurations

When using Sequelize to query data, I've noticed that 'Id' is automatically added to the end of my column name. How can I prevent this from happening? Below is an example of the entity data Model for Sequelize that I have created: function ...

Component re-rendering and initializing useReducer

I made some revisions to this post. Initially, I shared the entire problem with my architecture and later updated it to focus directly on the issue at hand in order to make it easier for the community to provide assistance. You can now jump straight to the ...

Error code ERR_UNESCAPED_CHARACTERS is being returned for a basic inquiry made on a particular URL

Issue Summary When accessing the URL https://www.eponuda.com/graficke-kartice-cene/gigabyte-radeon-rx-6900-xt-16gb-gddr6-2‎56-bit-gv-r69xtgaming-oc-16gd-graficka-kartica-cena-579068, an error is returned, while other URLs such as https://www.eponuda.com ...

Prevent access to Express routes until the route has completed its execution

I am currently working on an Express REST-API route that involves various database actions. My goal is to prevent any other calls from being made to the REST-API until the actions within this particular route have been completed. When this route is access ...

I'm surprised by the fact that array.findIndex is not functioning properly. According to Mozilla, it should be working fine

It was necessary to change state.findIndex to state.ids.findIndex in order to resolve the issue I was facing. However, an unexpected behavior occurs when calling the function onClick, as it automatically updates ALL of the active values to true, instead o ...