Passing data between parent and child components within an Angular application using mat tab navigation

I am currently working on a project, which can be found at this link.

Current Progress: I have implemented a mat tab group with tabs inside the app-component. When a tab is clicked, a specific component is loaded. Initially, most of the data is loaded in the app-component and then passed to the child components when a tab is clicked.

Desired Outcome: I want the link to add paths when clicking on a tab within the mat tab group. I believe by defining navbar paths, we can achieve this functionality in Angular.

Areas of Confusion: Although I am passing data to child components, I am unsure how to pass that data through the mat tab link. Specifically, I aim to create a navigation bar where clicking on a tab will change the path (e.g., localhost:4200/datatable), load the component, and pass data from the parent component. Currently, all mat tabs share the same link, but I plan on adding features that require reloading specific paths in the future.

Example Scenario: Upon entering the webpage, if a user clicks on the "datatable" tab, the path should change to localhost:4200/datatable. The app-component should then pass an object containing data for the datatable component to be correctly displayed under the respective tab.

My current implementation of mat tab:


<mat-tab-group animationDuration="0" (selectedTabChange)="onTabChanged($event)">
<mat-tab label="Add Expense" routerLink="/input">
  <app-expense-input [badgeCounter] = "badgeCounter" (countChanged)="countChangedHandler($event)"></app-expense-input> 
</mat-tab>

<mat-tab>
  <ng-template mat-tab-label>
    <span matBadge={{badgeCounter}} matBadgeOverlap="false" matBadgeColor="accent">Datatable</span>
  </ng-template>
  <ng-template matTabContent>
  <app-data-table [expensesList] = "expensesList" [badgeCounter] = "badgeCounter" 
  (countChanged)="countChangedHandler($event)"
  (countReset)="countResetHandler($event)"></app-data-table>
</ng-template>
</mat-tab>

<mat-tab label="Chart">
    
  <ng-template matTabContent>
    <app-highcharts></app-highcharts>
  </ng-template>
</mat-tab>

</mat-tab-group>

Attempted code for navigation:


<nav mat-tab-nav-bar [backgroundColor]="background">
  <a mat-tab-link routerLink ="/input"> Input</a>
  <a mat-tab-link routerLink ="/datatable">Datatable</a>
  <a mat-tab-link routerLink="/chart">Chart</a>
</nav>

The navigation works well, but my challenge lies in figuring out how to pass data (such as [expensesList]) via the anchor tags.

Thank you in advance for your assistance. Apologies if this question has been asked before; I have searched extensively but couldn't find a solution.

Answer №1

Have you ever considered why the api call is being made in your app-component? A better approach would be to transfer this code from the app-component to the data-table component inside the ngOnInit function:

this.apiService.getExpenses()
.subscribe(data => this.expensesList = data);

In doing so, the api call will only happen when a user accesses that specific tab.

On the other hand, if your intention is to preload this data upon the initial loading of the app, then you should store the result of the API call in a BehaviourSubject provided by the RXJS library. Afterwards, you can subscribe and retrieve the data from the data-table component.

Update: I have modified the stackblitz example to incorporate BehaviourSubjects https://stackblitz.com/edit/github-awefqi?file=src/app/services/api.service.ts

I have introduced a BehaviourSubject in the api-service, initialized with a test value. Subsequently, I invoke the apiService.getExpenses() within the app-component.

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

What is the best way to send the value from a textbox to this script?

My challenge is with this particular textbox: <input type="text" autocomplete="off" required="required" id="bar" name="bar" class="form-control" placeholder="Barcode"> Also, there's a button in the mix: <button type="button" style="float:r ...

Node.js: Calculating the number of requests processed per second in the http.get()

In my node.js project, I am creating a simple application for sending HTTP requests. var http = require('http'); var options = { host: 'www.example.com', port: 80, path: '/index.html' }; for(var i = 0; i < 500; i++ ...

Is it possible to incorporate a nested form in Angular reactive forms without utilizing an array?

this.parentForm = this._fb.group({ testControl1: [], testControl2: [], testChildForm1: this._fb.group({ testChildControl1: [], testChildControl2: [] }) )}; The parent form in the code above has two form controls and on ...

Once the data being interpolated undergoes a change, implement a setTimeout function in Angular 7

To hide the element with a specific value when displayed I attempted to monitor the incoming message (which changes from an old value to a new one) and added a timeout to the new message. However, there is a delay between the message arriving and appearin ...

When using the v-for directive with an array passed as props, an error is

I encountered an issue while passing an array of objects from parent to child and looping over it using v-for. The error message "TypeError: Cannot read property 'title' of undefined" keeps appearing. My parent component is named postsList, whil ...

Unusual output from the new Date() function: it displays the upcoming month

Your assistance and explanation are greatly appreciated. I have created a method that is supposed to return all the days of a given month by using two parameters- the year and the month: private _getDaysOfMonth(year: number, month: number): Array<Date& ...

Building state from multiple child components in Next.js/React: Best Practices

To better illustrate this concept, I suggest checking out this codesandbox link. This is a follow-up to my previous question on Stack Overflow, which can provide additional context. Currently, when interacting with the child elements (such as inputs), th ...

Troubleshooting: Angular input binding issue with updating

I am currently facing a challenge with connecting a list to an input object in Angular. I was expecting the updated values to reflect in the child component every time I make changes to the list, but strangely, the initial values remain unchanged on the sc ...

The next.js router will update the URL without actually navigating to a new page, meaning that it will still display the current page with the updated URL

My search results are displayed at the route /discovery, and I am working on syncing the search state with URL query parameters. For example, if a user searches for "chicken," the URL becomes /discovery?query=chicken&page=1. When a user clicks on a se ...

Incorporate user input into Alert Dialog Boxes

Would you be able to assist me in displaying the input value from the "email" field in my alert box? The code seems to be working fine, but I'm having trouble getting the alert box to show the email form value. I decided to use Bootstrap for som ...

I am wondering how to use the value assigned to a variable's textContent as an argument for player input in my JavaScript code

i am currently developing a JavaScript project to create a user interface for my rock, paper, scissors game. Currently, the game only runs in the console and prompts the player for input. So far, I have implemented three buttons (one each for rock, paper, ...

What is the process for updating tabs and their content in React?

Here is where the error occurs in my JavaScript code. I have successfully implemented it in HTML, CSS, and simple JavaScript, but encountered issues when trying to do so in React. My goal is to switch tabs and their corresponding data/content: ...

The integration of HTML and CSS using ng-bind-html appears to be malfunctioning

<ion-item ng-bind-html="renderHtml(word[key])"> </ion-item> When referring to word[key], it represents: <ul> <li>item 1</li> <li>item 2</li> <li>item 3</li> </ul> This is the CSS being u ...

Utilizing a Meteor Method within a Promise Handler [Halting without Throwing an Error]

I've been working on integrating the Gumroad-API NPM package into my Meteor app, but I've run into some server-side issues. Specifically, when attempting to make a Meteor method call or insert data into a collection within a Promise callback. Be ...

How can I parse JSON in React using the Parse function?

I am currently working with three list components, and when I click on any item in the tree list, it displays the JSON data. However, I would prefer to view it in a parse format rather than JSON. I attempted to use let json = JSON.parse(this.props.node, n ...

Refresh numerous HTML <div>'s using data from a JSON object

Looking to automatically update the homepage of my website with the ten most recent "posts" from the server. Here's an example HTML format: <div id="post1"> <p id="link"> </p> </div> <div id="post2"> <p id="li ...

Iterating through textboxes and buttons to trigger actions in JavaScript

Having an issue with JavaScript (or jQuery) where I can successfully input text and click a button on a page using the following script: document.getElementsByName('code')[0].value='ads0mx0'; document.getElementsByName('event&a ...

What is the process for transforming a nested dictionary in JSON into a nested array in AngularJS?

I am looking to create a form that can extract field values from existing JSON data. The JSON I have is nested with dictionary structures, but I would like to convert them into arrays. Is there a way to write a recursive function that can retrieve the key ...

The transitionend event fails to trigger if there is no active transition taking place

Take a look at this: http://jsfiddle.net/jqs4yy0p/ JS $('div').addClass('switch').on('transitionend', function(e){ alert('end'); }); CSS div { background-color: red; /*transition: background-colo ...

How to Use ngFor to Create a Link for the Last Item in an Array in Angular 7

I need help with adding a link to the last item in my menu items array. Currently, the menu items are generated from a component, but I'm unsure how to make the last item in the array a clickable link. ActionMenuItem.component.html <div *ngIf= ...