Angular 7: Efficiently Implementing Multiple Cascading Combobox Components

My component is designed to handle the management of cascading countries and states. When I input only one country and state in the form, everything functions perfectly. However, if I input three countries and states, the system malfunctions as shown in the example below. How can I resolve this issue?

Example with One country-state (working)

Stackblitz

Example with Three country-state (NOT working)

Stackblitz

Answer №1

There are two elements in this code snippet that are referencing the same variables:

<app-country [studentForm]="studentForm"></app-country>
<app-state [studentForm]="studentForm"></app-state>

<br/><br/>

<app-country [studentForm]="studentForm"></app-country>
<app-state [studentForm]="studentForm"></app-state> 

Both components have access to the same property of the studentForm class. To have each component group filled separately, you need to make some changes:

app.component.ts:

 this.studentForm = new FormGroup({
  'studentName':new FormControl(''),
  'countryId1': new FormControl(''),
  'stateId1': new FormControl(''),
  'countryId2': new FormControl(''),
  'stateId2': new FormControl('')
})

app.component.html:

<app-country [studentForm]="studentForm" [id]="'countryId1'"></app-country>
<app-state [studentForm]="studentForm" [id]="'stateId1'" [countryId]="'countryId1'"></app-state>

<br/><br/>

<app-country [studentForm]="studentForm" [id]="'countryId2'"></app-country>
<app-state [studentForm]="studentForm" [id]="'stateId2'" [countryId]="'countryId2'"></app-state>

In your country and state components, make sure to use countryId1/countryId2 and stateId1/stateId2 respectively (and modify country and state components to use the 'id' parameter).

UPDATE

In country.component.ts, add:

@Input() id: string;

In state.component.ts, add:

@Input() id: string;
@Input() countryId: string;

get states(): State[]{
   var val = this.studentForm.controls[this.countryId].value;
   return this.selectService.filterStates(val);
};

In country/state.component.html, change to:

<select [formControlName]="id">...

In select.service.ts, change:

filterStates(countryId){
   if(!countryId) return null;
   return this.getStates().filter((item) => item.countryid == countryId);
}

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

Is there a way to utilize ng-if within a button to reveal the remaining portion of a form using TypeScript?

Can anyone help me figure out how to make the rest of my form appear when I click on a button? I think I need to use Ng-if or something similar. Here is the code for the button: <button type = "button" class="btn btn-outline-primary" > Données du ...

What could be causing the error "Type 'String' cannot be used as an index type" to appear in my TypeScript code?

My JavaScript code contains several associative arrays for fast object access, but I'm struggling to port it to TypeScript. It's clear that my understanding of TypeScript needs improvement. I've searched for solutions and come across sugges ...

Creating a TypeScript interface where the type of one property is based on the type of another property

One of my Interfaces has the following structure: export enum SortValueType { String = 'string', Number = 'number', Date = 'date', } export interface SortConfig { key: string; direction: SortDirection; type: Sort ...

Enhancing Angular ngbDatepicker functionality by incorporating context into the markDisabled feature

In my code, I have defined an input field with ngbDatepicker. To disable certain days, I am using [markDisabled]="getDisabledDays" as shown below: <input type="text" [minDate]="getMinDate()" [maxDate]="maxDate" formControlName="deliverydate" #d= ...

What is the best way to implement a switch case for the value of a property within an object in a TypeScript file?

The object I'm dealing with looks like this: {a: auth?.type === '1' || auth?.type === '2' || auth?.type === '3' ? { reason: // I need to implement a switch case here : un ...

Chrome Driver Protractor Angular 2 encountering issue with unclickable element

My issue is with clicking the second level menu options to expand to the third level. I have tried using browser.driver.manage().window().setSize(1280, 1024) in the before all section. Here is my code snippet: it('Should trigger the expansion of the ...

Attempting to dynamically load an angular2 component upon the clicking of a tab has been my latest endeavor

Currently, I have multiple components loaded on page load within different tabs by using their selectors during design time. However, I am looking to dynamically load those components upon user demand, specifically when a tab is clicked. The issue arises ...

Transform the dynamic JSON format into a key-value pair structure with nested children nodes

Looking to convert a dynamic JSON structure into a tree node: { "video": { "width": 1920, "height": 1080, "video_codec": "H264", "CBR": "4337025", "frame_rate& ...

Despite providing a type, Typescript continues to display an error claiming that the property 'children' does not exist on the type 'FC<ProvidersProps>'

I have set up the props interface, but I am still encountering an error. Property 'children' does not exist on type 'FC'. 'use clilent' import React, { FC, ReactNode } from 'react' import { Toaster } from 'rea ...

Prevent side menu from automatically hiding when clicking on the heading

My menu is set up with headings and subheadings. When I click on the headings, it expands to display the corresponding subheadings, but it automatically collapses when clicking on the headings. I want it to stay expanded when clicking on the headings. He ...

Error encountered while attempting to load SWC binary for win32/ia32 in a Next JS application

Upon installing a Next.js app using the command npx create-next-app@latest, I encountered an error while running the app. Can anyone explain why this error occurred and provide a solution? PS D:\New folder\my-app> npm run dev [email pr ...

typescript code may not display a preview image

I recently came across a helpful link on Stack Overflow for converting an image to a byte array in Angular using TypeScript Convert an Image to byte array in Angular (typescript) However, I encountered an issue where the src attribute is not binding to t ...

Is there a way to dynamically adjust the size of mat dialog content to match the size of the mat dialog in

I have adjusted the size of my mat dialog, but the content is still stuck at the original size. To illustrate, here are some images: https://i.stack.imgur.com/2lLV2.jpg After researching, I found that it can be resized using CSS. I attempted the followin ...

What are the steps to integrate webpack with .NET 6?

Struggling to incorporate webpack into .NET 6 razor pages. The existing documentation online only adds to my confusion. Here is a snippet from my file1.ts: export function CCC(): string { return "AAAAAA"; } And here is another snippet from ...

Tips on ensuring dispatch is finished before accessing store data. Ngrx dilemma

Is there a way to ensure that a dispatch is completed before selecting from a store? I haven't had any luck finding a solution online. How can I make sure the dispatch finishes before selecting from the store? I would appreciate any help with my code ...

A new Angular project has been created and saved at /.gitkeep

When attempting to create a new Angular project using the ng new command, the process begins but gets stuck at certain points. The creation of crm_ng/src/assets/.gitkeep (0 bytes) is completed successfully. However, while installing packages with npm, the ...

Zod vow denial: ZodError consistently delivers an empty array

My goal is to validate data received from the backend following a specific TypeScript structure. export interface Booking { locationId: string; bookingId: number; spotId: string; from: string; to: string; status: "pending" | "con ...

Error Encountered While Building AWS Amplify with Ionic 5 and Angular 10

Our team is currently facing a challenge at my company that we've been struggling to resolve, and I was hoping someone here could offer some assistance. We are using AWS Amplify in our Angular 10/Ionic 5 project, and encountering the following error: ...

Getting the Most Out of .find() in Angular 4

Despite reading various similar questions, I'm still struggling to make the .find() function work in my application. I have a service with the following API: export class VehicleService { private defUrl = 'API'; constructor(private ht ...

Using Typescript: Generate keys in function return depending on parameter

Currently in the process of developing an SDK for a Rest API that includes an embed request parameter to fetch additional resources and add them to the response. I am exploring if there is a way, using Typescript, to extract these embed parameters while de ...