Is there a way to modify component data in Angular 5 from another component?

I have a dashboard setup where the main component stays consistent across all pages, while another component, the load component, changes based on the router-outlet. My goal is to hide the "manage load" button in the dashboard component if I delete all loads in the manage load component. Despite my efforts and online research, I am unable to resolve this issue. Any assistance would be greatly appreciated. here is the HTML code for my dashboard component:

<div class="container-fluid">
        <div class="row">
            <div class="col-lg-3 side-nav">
                <div class="panel">
                    <div class="welcome">
                        <img src="assets/img/welcome.png" class="img-responsive" alt="">
                    </div>
                    <nav class="navbar navbar-default">
                        <div class="container-fluid">
                            <div class="navbar-header">
                                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#side-navbar" aria-expanded="false">
                                    <span class="sr-only">Toggle navigation</span>
                                    <span class="icon-bar"></span>
                                    <span class="icon-bar"></span>
                                    <span class="icon-bar"></span>
                                </button>
                            </div>
                            <div class="collapse navbar-collapse" id="side-navbar">
                                <ul class="nav nav-pills nav-stacked btn-collpase panel_show collapse in">
                                    <li routerLinkActive="active">
                                        <a href=""  routerLink="/dashboard">Dashboard</a>
                                    </li>
                                    <li routerLinkActive="active">
                                        <a href="" routerLink="/dashboard/postLoad">Post Load</a>
                                    </li>
                                    <li *ngIf="this.loads.length > 0">
                                        <a href="" routerLink="/dashboard/manageLoad">Manage Loads</a>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </nav>
                </div>
            </div>
            <div class="col-lg-9">
                <router-outlet></router-outlet>
            </div>
        </div>
        <hr>
        <div class="clearfix"></div>
    </div>

And here is the TypeScript file for the dashboard component:

import { Component, OnInit } from '@angular/core';
    import {TruckService} from "../services/truck.service";
    import {LoadService} from "../services/load.service";
    import {Observable} from "rxjs/Observable";

    @Component({
        selector: 'app-dashboard',
        templateUrl: './dashboard.component.html',
        styleUrls: ['./dashboard.component.css']
    })
    export class DashboardComponent implements OnInit {
        loads  = [];
        constructor(private loadService:LoadService) { }

        ngOnInit() {
            this.loadService.getLoads().subscribe(data=>{
                this.loads = data;
                console.log("load data is "+data);
            });
        }

    }

Here is the HTML content for the manage load component:

<div *ngIf="loads.length > 0">
<h3>Your Loads</h3>
<table class="table-responsive table-stripped table-bordered tab" width="90%;">
    <thead style="text-align: center;">
    <tr style="padding: 5px;">
        <td>From</td>
        <td>To</td>
        <td>Weight</td>
        <td>Date</td>
        <td>Action</td>
    </tr>
    </thead>
    <tr style="height: 40px;text-align: center;vertical-align: middle;" *ngFor="let load of loads">
        <td style="">{{load.from_name}}</td>
        <td>{{load.to_name}}</td>
        <td>{{getLoadWeight(load.truck_capacity_id)}}</td>
        <td>{{ toDate(load.posted_at)}}</td>
        <td><button class="btn btn-primary" routerLink="/dashboard/viewTrucks/{{load.id}}">View Trucks</button>
            <button class="btn btn-danger" (click)="deleteLoad(load.id)">Delete Load</button>
        </td>
    </tr>
</table>

Any help with this issue would be greatly appreciated.

Answer №1

It seems like the issue you're facing involves fetching a large amount of data in your dashboard component from the database via a service call. Updating one component's data from another component can be tricky, especially if the other component hasn't loaded yet.

One solution could be to set up the fetch load service to run automatically every 5 seconds. This way, when you make updates in the manage loads component and then switch to the dashboard component, it will fetch the most recent data from the database at regular intervals.

An alternative approach would be to use an Anonymous Subscription for making API calls. By importing AnomymousSubscription, creating its object, and setting up a timer and function to continuously hit the API, you can ensure that data is constantly being updated.

I hope these suggestions provide some clarity and help you find a suitable solution to your problem.

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

Iterating through elements within the ng-content directive in Angular using *ngFor

Is it possible to iterate through specific elements in ng-content and assign a different CSS class to each element? Currently, I am passing a parameter to enumerate child elements, but I would like to achieve this without using numbers. Here is an example ...

Unable to employ a custom Typescript .d.ts file

Currently, I am delving into learning TypeScript and encountering a hurdle while attempting to define a class in a TypeScript definition file and then utilize it in a TypeScript file. The dilemma lies with a JavaScript "class" called "Facade," which serve ...

How to display a PDF in Angular 6 using a byte array retrieved from a WebAPI

Having trouble opening a PDF from byte array sent by WebAPI. This is my Service: fetchPdfDocument(): Observable<any> { return this.httpClient .get(this.configuration.serverUrl + this.configuration.getPdfDoc, { re ...

Resolving Circular Dependency Error in Angular Component due to Service Integration Testing

Delving into Angular Unit Testing has been a recent focus of mine as I've begun incorporating mock tests in one of my projects. However, I've hit a roadblock with an error popping up in one of my component tests: Error: NG0200: Circular dependen ...

Leverage the JSON Web Token module within a Chrome extension

Currently in the process of developing a chrome extension but encountering an issue with loading the json web token node module in my Node.js setup. background-script.ts import jwt from 'jsonwebtoken'; // import * as jwt from '../node_mod ...

Tips for implementing a feature in Angular 6 that enables an input box to accept both negative and positive values within the range of 0 to

HTML markup <input type="number" min="0" max="100" required placeholder="Charge" [(ngModel)]="rateInput" name="rateInput" [formControl]="rateControl"> Implementing TypeScript validation this.rateControl = new FormControl("", [Validators.max(100) ...

Retrieve data from a table within an Angular component

Struggling with the ng2-smart-table library, I am facing challenges in passing values entered in the edit line to a custom component: Refer to the code snippet below for passing Maximum and Minimum Temperature values to the SmartTableEditorFunctionsCompon ...

A guide on increasing the NPM semantic version and generating a tag through the utilization of Pull Request Labels within a GitHub Actions workflow

My GitHub Actions workflow triggers whenever a pull request is created into the develop branch. The main purpose of this workflow is to automatically increase the npm version of my Angular project and create a corresponding tag. Even though the workflow jo ...

Upon attempting to run ionic for iOS, an error was encountered regarding the arm64 and armv7 architectures

I'm currently in the process of developing a mobile application for both Android and iOS platforms utilizing Ionic version 1. Here is a breakdown of the software versions I'm working with: cordova: 7.0.1 ionic: 2.2.2 ios-deploy: 1.9.2 ios-sim: ...

Error message in Angular Reactive Forms: Control with specified path cannot be found

My current challenge lies within the component: cabinet-clinic-form.component.ts. I am facing an issue with FormGroup validation in my clinics FormArray. Upon rendering the page, I encounter an error as shown in this screenshot. Despite attempting to dynam ...

The Capacitor Community Electron Platform, which combines IONIC, Angular, and Electron, encountered a TypeError: [ERR_INVALID_ARG_TYPE]. This error message indicates that the "path" argument must be in the

I have been attempting to follow the guidelines provided on to integrate the Capacitor Community Electron into a brand new Ionic Angular Test App. Everything is going smoothly until I reach the step where I need to add the platform as per the instructions ...

Chrome fails the karma tests while phantomjs passes them

I've been struggling with this issue for some time now and can't seem to find a solution. I'm working on an Ionic 2 project that utilizes Angular 2's testing environment. When I run 'ng test' using Karma's Chrome launcher ...

How to showcase a nested list using Angular 2

I need assistance with displaying a nested list structure. Here is an example of the list: [ { name: "Level 1A", children: [ { name: "Level 2A", children: [ ...

Having trouble retrieving the SSM Parameter during deployment using CDK

Currently, I am facing a strange issue as I attempt to retrieve a parameter for my pipeline using the CDK SSM Parameter library: CfnParameter at 'nonProdAccountId.Parameter' should be created in the scope of a Stack, but no Stack found Despite t ...

Setting up React Context API with TypeScript: A Step-by-Step Guide

I recently updated my app.js file to app.tsx for improved functionality. However, I encountered an error with the current value. app.tsx import React, { createContext, useState } from "react"; import SelectPage from "./pages/select/select& ...

Include a control within a form based on the Observable response

I am looking to enhance my form by adding a control of array type, but I need to wait for the return of an Observable before mapping the values and integrating them into the form. The issue with the current code is that it inserts an empty array control e ...

Button for enabling and disabling functionality, Delete list in Angular 2

I am looking to toggle between the active and inactive classes on a button element. For example, in this demo, there are 5 buttons and when I click on the first button it removes the last one. How can I remove the clicked button? And how do I implement the ...

Displaying a portion of the chart's key in a Highcharts BarChart

I need assistance displaying a partial legend (such as min, medium, max) for the X and Y axes, along with a horizontal dashed line at the medium point of the Y axis in a HighCharts BarChart. The graph is compact on the screen, serving as a summary of multi ...

Unable to remove item from store using NgRx is causing issues

I recently started learning NgRx and decided to build a small app for practice. The app consists of two text fields where users can add items to a list, which is then displayed on the screen. While I successfully managed to add items to the list, I encount ...

Oops! An error occurred: plugin_not_installed cordova plugin Filepath along with File Chooser. Please make sure to install the required plugins

Currently, I am utilizing the FilePath and File Chooser Plugin to select an attachment and then convert it into base 64. To install Filepath, I used the following commands: npm install cordova-plugin-filepath npm install @ionic-native/file-path For File ...