What is the best way to retrieve matching values based on IDs from an imported table?

How can I retrieve values that match on ID with another imported table? My goal is to import bank details from another table using the ID and display it alongside the companyName that shares the same ID with the bank details.

I've attempted several options but none have worked so far.

Thank you, and please keep it simple as I'm still in the learning process :)

Interfaces:

export interface Company {
  id: number;
  companyName: string;
  address: string;
  estimatedRevenue: number;
}

export interface Bank {
  id: number;
  bankName: string;
  bankAccountNumber: string;
}

Component:

import { Component, OnInit } from '@angular/core';
import { Company } from '../_models/company';
import { AlertifyService } from '../_services/alertify.service';
import { CompanyService } from '../_services/company.service';

import { timer } from 'rxjs';
import { AddCompanyComponent } from '../add-company/add-company.component';
import { Bank } from '../_models/bank';
import { BankService } from '../_services/bank.service';

@Component({
  selector: 'app-company',
  templateUrl: './companies.component.html',
  styleUrls: ['./companies.component.css'],
})
export class CompaniesComponent implements OnInit {
  selectedCompany: Company;
  companies: Company[];
  banks: any;
  selectedCompanyBank: Bank[];
  bankvalueid: number;
  bankNameany;
  bankName: string;

  constructor(
    private companyService: CompanyService,
    private alertify: AlertifyService,
    private bankService: BankService,
  ) {}

  ngOnInit() {
    this.loadCompanies();
  }

  async loadCompanies() {
    this.companyService.getCompanies().subscribe(
      (companies: Company[]) => {
        this.companies = companies;
      },
      error => {
        this.alertify.error(error);
      },
    );
  }

  async loadBanks() {
    this.bankService.getBanks().subscribe(
      (banks: Bank[]) => {
        this.banks = banks;
      },
      error => {
        this.alertify.error(error);
      },
    );
  }

  //  companyChange() {
  //    this.bankName = this.banks.find((bank) => bank.id ===
  //     this.selectedCompany.id).bankName;
  // }
}

HTML:

<div id="selectCompanyDiv">
  <ng-container *ngIf="companies">
    <div class="col-12 col-md-3 col-xl-2 mt-5 bd-sidebar">
      <label for="">Select Company</label>
      <!-- <select class="form-control" [(ngModel)]="bankvalueid" [(ngModel)]="selectedCompany"> -->
      <select class="form-control" [(ngModel)]="selectedCompany">
        <option *ngFor="let each of companies" [ngValue]="each">{{
          each.companyName
        }}</option>
      </select>
    </div>
  </ng-container>

  <br />
  <br />

  <ul *ngIf="selectedCompany" class="list-group list-group-flush">
    <li class="list-group-item">Company name: {{ selectedCompany.name }}</li>
    <li class="list-group-item">
      Company address: {{ selectedCompany.address }}
    </li>
    <li class="list-group-item">
      Company Estimated revenue: {{ selectedCompany.estimatedRevenue }}₪
    </li>
    <button>Show more information</button>
  </ul>
</div>

<div *ngIf="selectedCompany" class="card" style="width: 18rem;">
  <div class="card-body">
    <h5 class="card-title">{{ selectedCompany.companyName }} {{ bankName }}</h5>
    <h6 class="card-subtitle mb-2">Location: {{ selectedCompany.address }}</h6>
    <br />
    <h6 class="card-subtitle mb-2">
      Estimated revenue: {{ selectedCompany.estimatedRevenue }}₪
    </h6>
    <p class="card-text">
      Some quick example text to build on the card title and make up the bulk of
      the card's content.
    </p>
    <a href="#" class="card-link">Edit Information</a>
    <a href="#" class="card-link">Another link</a>
  </div>
</div>

<!--
<h4>Basic native select</h4>
<mat-form-field>
  <mat-label>Select Company</mat-label>
  <select  matNativeControl [(ngModel)]="selectedCompany">
    <option value="" disabled selected>Select</option>
    <option *ngFor="let value of companies" [ngValue="value"]{{value.name}}></option>
  </select>
</mat-form-field>
-->

Answer №1

Utilize ngModelChange

HTML:

<select  class="form-control" [(ngModel)]="selectedCompany" (change)="companyChange()">

To show the bank name beside the company name:

<h5 class="card-title">{{selectedCompany.companyName}} {{bankName}}</h5>
<h6 class="card-subtitle mb-2">Location: {{selectedCompany.address}} </h6>

In TS:

Define a variable called bankName

bankName:string; 

ngOnInit() { 
   this.loadCompanies(); 
   this.loadBanks() ;
}

companyChange(){
if(this.banks.length>0){
 this.bankName=this.banks
 .find((bank)=> bank.id == selectedCompany.id).bankName;
 } 
}

Example in js:

this.banks=[
   {
     bankName:"CITI",
     id:1
   },
   {
     bankName:"HDFC",
     id:2
   }
];
let selectedCompany={
   companyName:'Example Company',
   id:2
}
let bankName=this.banks.find((bank)=> bank.id == selectedCompany.id).bankName; 
console.log(bankName);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Encountering issues with integrating interactjs 1.7.2 into Angular 8 renderings

Currently facing challenges with importing interactive.js 1.7.2 in Angular 8. I attempted the following installation: npm install interactjs@next I tried various ways to import it, but none seemed to work: import * as interact from 'interactjs'; ...

Ways to fix a "define is not defined" issue when utilizing jasmine karma with compiled typescript for component testing

I'm faced with an issue in my typescript app where the compiled code is stored in a single file named myjs.js within the js folder. Additionally, I have karma jasmine configured on my workspace. Inside myjs.js, there's a segment of code like thi ...

The error states that the type '() => string | JSX.Element' cannot be assigned to the type 'FC<{}>'

Can someone help me with this error I'm encountering? I am fairly new to typescript, so I assume it has something to do with that. Below is the code snippet in question: Any guidance would be greatly appreciated. const Pizzas: React.FC = () => { ...

Why does my Observable remain perpetually unfulfilled?

I recently started learning javascript and came across the Angular 2 Documentation where I discovered that Promises can be replaced with Observables. While experimenting with a simple code, I noticed that in addition to the expected result, I am also getti ...

Angular2 context refers to the 'from' method of Observable

Within the constructor of my Angular2 component class, I have included the following code: Observable.from([1,2,3]).subscribe(e=>{ console.log(e); }); I have made sure to import the necessary modules: import { Observable } from ' ...

bootstrap5 is unable to transform an undefined or null value into an object

Struggling to implement a new modal using Angular 11 and Bootstrap 5, encountering the following error: ERROR TypeError: Cannot convert undefined or null to object at Function.keys (<anonymous>) at Object.getDataAttributes (bootstrap.esm.js:8 ...

Transforming a JSON object into XML format

Currently, I am encountering an issue while attempting to convert my JSON object to XML using the xml-js library's json2xml function. When trying to implement this functionality, I keep getting an error message that states: Error: Buffer is not defin ...

Disabling sound feature in the "mat-video" npm package

Currently, I've implemented the mat-video package (npm i mat-video) in my angular application to facilitate video playback. It's been working quite well. <mat-video style="min-height: 30%" quality="false" title="My Tutorial Title" loo ...

Tips on changing the date format in Typescript to the desired format

My date string reads as 2016-09-19T18:10:31+0100. Here's what I'm doing: let dateString:string = 2016-09-19T18:10:31+0100; let newDateString:Date = new Date(dateString); The output I'm currently getting is Tue Sep 19 2016 18:10:31 GMT+0530 ...

What is a superior option to converting to a promise?

Imagine I am creating a function like the one below: async function foo(axe: Axe): Promise<Sword> { // ... } This function is designed to be utilized in this manner: async function bar() { // acquire an axe somehow ... const sword = await foo ...

Conceal the current component when navigating in Angular 2

When I swipe on the app.component, I am being redirected to another component. However, the content of the other component is not fully displayed as it is also showing the content of the app.component. How can I hide the app.component content and only di ...

Utilizing material-ui with Autocomplete featuring various value and option types

In my code, I am looking to store only an option's ID in a value For autocomplete functionality, the value's type and the option's type need to be the same My solution was to change the value in onChange, which worked successfully However ...

Transferring information from a chosen <mat-option> to a different component in Angular Material

I am currently facing an issue with two components in my Angular application. The first component includes an Angular Material mat-option to select an option from a dropdown menu, while the second component is supposed to display the selected data. I attem ...

The error message "Cannot access the 'id' property of undefined within Angular forms" is indicating that there is

I've been working on an Angular application that includes a parent component (products) for listing details with pagination, as well as a child component (Product Details) to view individual product details using Angular forms. The form successfully l ...

Warning: The gulp_jspm module is now deprecated and will be removed

Whenever I run gulp_jspm, a DeprecationWarning pops up. Is there an alternative method to generate my bundle files without encountering this warning? It seems like when I used gulp-jspm-build, I had to include some node files that were not necessary before ...

How to remove a variable definition in Typescript

Is there a way to reset a variable to undefined after assigning it a value? To check, I am using the Underscore function _.isUndefined(). I have attempted both myVariable = undefined and delete myVariable without success. ...

Troubleshooting issues with Docker and Angular 2: unable to retrieve data

We are in the process of setting up an Angular 2 application with Docker by following a tutorial available at: https://scotch.io/tutorials/create-a-mean-app-with-angular-2-and-docker-compose Although the application deploys successfully, we encounter an i ...

An unexpected issue occurred while attempting to create a new Angular app using the command ng

Currently in the process of deploying my angular application and utilizing Infragistics. Following their Documentation, I used npm install Infragistics for installation. However, when I run ng new --collection="@igniteui/angular-schematics" I e ...

Utilizing constants within if statements in JavaScript/TypeScript

When working with PHP, it is common practice to declare variables inside if statement parenthesis like so: if ($myvar = myfunction()) { // perform actions using $myvar } Is there an equivalent approach in JavaScript or TypeScript?: if (const myvar = myf ...

405 we're sorry, but the POST method is not allowed on this page. This page does

I'm currently working on a small Form using the kit feature Actions. However, I'm facing an issue when trying to submit the form - I keep receiving a "405 POST method not allowed. No actions exist for this page" error message. My code is quite st ...