Search code examples
angulartypescriptangular-changedetection

Change data based on dropdown selection from another non-related component Angular


I have non-related components. From the header component when I change company I need to show data match with the company which I selected from the header component. currently, it's working when I in another page and once visit that page it changes but I need to change it on time when I select 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);
    });
  } 

Solution

  • If I got your implementation right, currentCompany is something like a subject. At least you are subscribing to it.

    So you could put the refresh call for the branches into this subscription as well.

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

    You might end up with an unnecessary additional loading of the branches on initialisazion. If so, you could just remove the getBranches call in your afterViewInit.