Update information according to the drop-down choice made from a different, unrelated component in Angular

I have different components that are not related. When I select a company from the header component, I want to immediately display data that matches the selected company. Currently, the data changes only when I visit another page and then return, but I need it to update in real-time when I choose a company from the header.

Header.ts

  companyData: Company;
  companyId;

  getCompany() {
    this.companyService.getCompanies().subscribe(x =>
      this.companyData = x
    );
  }

  changeCompany(companyId) {
    this.systemFunction.changeCompany(companyId);
  } 

common service.ts

  private companySource = new BehaviorSubject('');
  currentCompany = this.companySource.asObservable(); 

  changeCompany(companyId: number) {
    this.companySource.next(String(companyId));
  } 

Branch.ts

  ngOnInit() {
    this.systemFunction.currentCompany.subscribe(cid => this.companyId = cid);
   this.systemFunction.changeCompany(this.companyId);
  }

  ngAfterViewInit() {
    this.getBranches();
  }

  getBranches() {
    this.branchService.getBranches().subscribe(b => {
      Object.assign(this.branchData, b);
      // tslint:disable-next-line:no-shadowed-variable
      this.branchData = this.branchData.filter(b => b.CompanyId == this.companyId);
    });
  } 

Answer №1

If I understand correctly, it seems that currentCompany acts as a subject in your implementation, with you subscribing to it.

Consider adding the refresh function call for branches within this subscription block.

this.systemFunction.currentCompany.subscribe(cid => {
    this.companyId = cid;
    this.getBranches();
});

Be mindful of potentially triggering an unnecessary extra loading of branches during initialization. If this occurs, you can simply omit the getBranches call in your afterViewInit method.

Answer №2

It appears that the expectation is to have the branchData re-evaluated once the companyId changes. However, since branches operate on their own subscription system, calling getBranches() will trigger the necessary updates.

If immediate reaction to company changes and subsequent branch updates is required, consider implementing:

ngOnInit() {
   this.systemFunction.currentCompany.subscribe(cid => refreshCompany(cid));
   this.systemFunction.changeCompany(this.companyId);
  }

  ngAfterViewInit() {
    this.getBranches();
  }

  getBranches() {
    this.branchService.getBranches().subscribe(b => {
       this.branchData = ...;
       this.refreshBranches();
    });
  }

  refreshCompany(cid) {
    this.companyId = cid;
    this.refreshBranches();
  }

  refreshBranches() {
    this.filtered = this.companyId ? 
       this.branchData.filter(b => b.CompanyId == this.companyId) : [...this.branchData];
  }

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

The ng2-image-viewer does not support the newest versions of Angular (11 and above)

Encountering an issue with ng serve: Error message: ERROR in node_modules/ng2-image-viewer/index.d.ts:3:22 - error NG6003: Appears in the NgModule.exports of SharedModule, but could not be resolved to a NgModule, Component, Directive, or Pipe class. This ...

Hover effect on Angular Material Stepper

Is there a way to apply CSS styles to a specific step (Angular material stepper) when hovering over it? I have attempted to set the styles on the elements .mat-step-header and mat-step, as well as applying a custom CSS class, but so far nothing has seeme ...

Modifying the appearance of a Component within a NavLink

I'm currently working on a navbar using NavLink from React-Router-Dom. It's fine to use the 'isActive' prop to style the active Link, but I'm stuck on how to style the subelements inside it. For more specific details, please take a ...

Establishing the value of "document.cookie"

Encountering issues while trying to set a cookie using different methods: Method 1: document.cookie = name + "=" + value + "; expires=" + date.toUTCString() + "; path=/"; This method only sets the value up to "name=value" wh ...

What is the best way to delete a purchase event that is being displayed on my webpage through Google Tag Manager?

Lately, I noticed that Google Tag Manager has been displaying a purchase event on my html. The data appears to be from a sample in development and I can't figure out why it's showing up below the footer of my page. Does anyone have any insight i ...

Implementing redux-persist with redux toolkit using TypeScript

Currently, I have been utilizing Redux Persist in my next js application but now I am interested in incorporating redux toolkit with TypeScript. While I have managed to grasp the syntax for implementing redux-persist in redux toolkit, I am struggling to ...

Sinon fails to mock the provided URL when GET request includes parameters

I am currently working on creating test cases for the services in my Angular application and encountering some challenges. Below is the code snippet for the service: /** * Sends http request to fetch client states and territories available for a specifi ...

Creating Instances of Variables Within a Class

Currently, I am working on a project using Ionic and Angular. I have come across various ways of instantiating variables and I'm unsure about the implications of each method. Here are three scenarios that confuse me: export class someClass { myVaria ...

The issue with importing fonts in CSS causing an error is encountered when utilizing an exported Angular library

I have a components library for Angular that relies on line-awesome icons. To include the necessary fonts and styles, I am using a CDN in the main SCSS file as shown below: @import url('https://fonts.googleapis.com/css2?family=Nunito:wght@200;300;400; ...

Outputting data stored in Firestore object

Is there a way to display the content of a Firestore object in Angular Firebase? I am working on a project where I need to retrieve and print the name of a document stored in Firestore. In my Firestore database, I have a parent collection called "nforms" w ...

Error: The utilization of the life cycle interface mandates the implementation of type checking

Currently, I am in the process of translating my typescript project to Webpack 2. While one project transitioned smoothly, I encountered an error with the other project... Error: use-life-cycle-interface necessitates type checking After conducting a br ...

Can I specify which modal or component will appear when I click on a component?

Working on a small Angular 5 project, I have a simple component that represents a food product shown below: [![enter image description here][1]][1] This component is nested within my main component. When this component is clicked, a quantity component/m ...

Unable to bind to ngModel as it returned as "undefined" in Angular 8

Whenever I bind a property to ngModel, it consistently returns undefined <div> <input type="radio" name="input-alumni" id="input-alumni-2" value="true" [(ngModel) ...

Showcasing regional JSON information on an Angular 9 template

I want to showcase the following JSON data in my HTML template [ { "Event Name": "Get All Information", "Info": "Retrieves all data stored in the system. Caution: this request returns more than 8MB and takes over 5 seconds", "Endpoint": "/ ...

The functionality of the Bootstrap collapse menu is not compatible with Angular

I'm experiencing difficulties with implementing the "collapse" effect in the menu using bootstrap and angular. I have set up the layout separately and everything seems to be functioning correctly, but as soon as I integrate angular, the menu stops wor ...

Unable to locate the next/google/font module in my Typescript project

Issue With Import Syntax for Font Types The documentation here provides an example: import { <font-name> } from 'next/google/font'; This code compiles successfully, but throws a "module not found" error at runtime. However, in this disc ...

Do the two types of updater functions for setState in React hold the same value?

Recently, I came across the concept of using updater functions for setState in React. After learning about this, I noticed it being implemented in two different ways. Imagine having a state object structured like this: interface State { readonly expand ...

Unable to load dynamic JSON data in ag-grid for Angular 2

ngOnInit(){ this.gridOptions = {}; this.gridOptions.rowData = []; this.gridOptions.rowData = [ {configName: 1, configName1: "Jarryd", configName2: "Hayne", configName3: "tttttt", configName4: "rrrtttt", configName5:"drrrrrr"}]; } ...

Badging with Angular, HTML, and Bootstrap

I've been attempting to integrate Bootstrap 5's badges into my Angular application, but they don't seem to be displaying correctly together. While using Angular 13, the html within the app-root component appears clustered without proper for ...

Discovering the origins of the node.js native modules and delving into the intricacies of typed modules

I am using a Windows machine and trying to locate where node fetches the source code for native modules. On my system, I can only find the @types file which contains "Typed Only" modules. For example, the module "assert" is available in the master/lib fold ...