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

My Nextjs project is encountering deployment issues with both Netlify and Heroku

Whenever I attempt to deploy my application on Heroku or Netlify, I encounter an ERROR related to an incorrect import path. It's perplexing because the import is accurate and functions properly locally. Log ./pages/_app.tsx:7:27 6:31:19 PM: Type err ...

Oops! It seems like there was a mistake. The ReferenceError is saying that Vue is

I've been working on creating a new app, but I keep running into an issue. Unidentified Reference Error: Vue is not recognized. <template> <v-app> <div id="example-1"> <v-btn v-on:click="counter += 1">Add 1</v-bt ...

Prevent selection based on JSON information

I am utilizing the Jiren filter library to sort through JSON data. If a particular filter criteria does not match any of the results, I would like to disable that option in the select dropdown. For instance, if "Silversea Expedition" is not found in my re ...

Service in Angular2 designed to retrieve JSON data and extract specific properties or nodes from the JSON object

Currently, I am trying to teach myself Angular2 and facing some difficulties along the way. I am working on creating a service that loads a static JSON file. Right now, I am using i18n files as they are structured in JSON format. The service will include a ...

Issues with JSON data not functioning properly when using file system in JavaScript

When attempting to parse a JSON file, I encountered some errors. The file is located in a directory within my JavaScript file, under the 'fs' in a folder named "recipes." Within this folder, there are 3 JSON files, each representing a separate ob ...

Alter the background color of the text input when it is selected for exit

How can I adjust the input field color when text is selected? I'm looking to get rid of the dark grey box highlighting. (Check out the image below) https://i.sstatic.net/OgWaz.gif <div id="ember1102" class="ember-view"> <i class="fa fa ...

Angular 8 form controls becoming unresponsive while the list is being loaded

Hello, I am currently experiencing an issue in Angular. I have a page with a basic Angular form and two independent components that load lists from an API (comments with 500+ records and posts with 500+ records). The Problem: While trying to enter values ...

Can dynamic placeholders be implemented for Angular 6 material inputs?

Currently, I am attempting to dynamically adjust the placeholder of a Material input field based on calculations that are taking place in the background. These calculations derive from the user's responses to other questions on the form. I have exper ...

Calculating the percentage in a jQuery Slider

For a while now, I've been using var slideWidth = 420; to set the width of sliders and then $('#slideInner').css('width', slideWidth * numberOfSlides); to calculate the total width of all sliders effectively in pixels. An Issue Ar ...

The drop-down list was designed with a main button to activate it, but for some reason it is not functioning properly. Despite numerous attempts, the list simply will not display as intended

<html> <body> <button onclick="toggle()" class="nm" > main</button> <div class="cntnr" style="display : none;"> <ul class="cnkid"> <li class="cnkid"><a class="cnkid" ...

Trouble with Bootstrap v4 toggle drop-down menu functionality detected in local environment, yet functions correctly when live on the

Today, I've encountered an issue with my Bootstrap v4 collapsible hamburger menu on my local XAMPP server. Interestingly, the menu works perfectly fine on my public website when the display is 768px wide in Chrome and Firefox. I have searched through ...

What steps can I take to resolve a CSS problem in an Angular Web Component within a React Application?

I recently integrated an Angular Web Component with some widgets from Angular Material UI into my simple React Application. While the functionality of the buttons, tables, and radio buttons is working perfectly fine, I am facing issues with the styling and ...

`How can I incorporate typography into my Angular Material design?`

For my angular app, I am developing a custom theme and incorporating bootstrap's reboot to establish a basic starting point for non-material elements. To avoid conflicts with material variables, I converted the reboot into a mixin. In this mixin, I pa ...

Combining multiple 'Eithers' and 'Promises' in fp-ts: A guide to piping and chaining operations

Recently, I began working with fp-ts and wanted to create a method with functional-like behavior that would: Parse a bearer token Verify the validity of the user using the parsed token import { Request } from 'express'; import { either } from & ...

Guide on sending a JSONP POST request using jQuery and setting the contentType

I'm struggling to figure out how to make a jsonp POST request with the correct content type of 'application/json'. Initially, I was able to send the POST request to the server using the jQuery.ajax method: jQuery.ajax({ type: ...

Samsung Galaxy S7 can interpret alphabetical parameters as numbers in a link sent via SMS

When trying to open a text message with a new message on my website using a link, I encountered an issue specifically with the Galaxy S7. The following code works on most Android phones: sms:5555555555?body=JOIN However, on the Galaxy S7, the "?body=JOIN ...

Tips for sending attributes to jQuery autocomplete

I'm facing a major issue with implementing a jquery autocomplete feature, and JavaScript isn't my strong suit. Currently, I'm using the jquery.auto-complete plugin available at: https://github.com/Pixabay/jQuery-autoComplete, which is an up ...

Having trouble displaying dynamically generated texture from a fragment shader in ThreeJS

I've been working on creating a texture using a Three.WebGLRenderTarget and then trying to access it in a fragment shader in the following stage. The concept is to execute the first stage once to generate a complex and costly SDF map, and then access ...

What is the best way to input individual students' CA and exam scores into distinct fields and then calculate their total scores in a separate text field?

As a beginner in jQuery, I am looking for guidance on creating a script that calculates the Total score, Grade, Remark, and Position based on the user input of CAT score and EXAM score. The result should be displayed dynamically once both scores are entere ...

Customize div styles according to the website domain

I want to dynamically change the header of my website based on whether it is in dev QA or production environment. Below is the HTML code: <div id="wrapper"> <form id="form1" runat="server"> <div class="wrapper"> <div> ...