How to dynamically set options in Angular 4 by value

I have 2 option sets (picklists) and I want to populate one based on the selection from the other. For example, consider the arrays in the ts file:

   carsArray: { id: number, name: string }[] = [
    { "id": 1, "name": "Car1" },
    { "id": 2, "name": "Car2" },
    { "id": 3, "name": "Car3" }
  ];

  carModulesArray:{ id: number, carId:number ,name: string }[] = [
    { "id": 1, "carId":1, "name": "Module1" },
    { "id": 2, "carId":1, "name": "Module2" },
    { "id": 3, "carId":1,"name": "Module3" },
    { "id": 4, "carId":2,"name": "Module4" },
    { "id": 5, "carId":3,"name": "Module5" }
  ];

And in the HTML template:

  <select id='cars'>
      <option *ngFor="let c of carsArray" 
      value="{{c.id}}">{{c.name}}</option>
    </select>

    <select id='modules'>
        <option *ngFor="let m of carModulesArray" 
        value="{{m.id}}">{{m.name}}</option>
      </select>

How do I dynamically populate the second picklist (modules) based on the selection from the first picklist (cars)? So, after selecting car 1, only modules 1, 2, and 3 should be visible. Similarly, selecting car 2 (or car 3) should show module 2 (or module 3).

Thank you for your assistance in advance.

Answer №1

With Alex's assistance, I have crafted the following code. While there is room for improvement, this is what I have come up with in HTML format:

<div class="form-group">
                <label for="carsId" class="col-sm-2 control-label">Cars</label>
                <div class="col-sm-10">
                  <select id='carsId' (change)="onCarsChange($event)">
                    <option *ngFor="let c of carsArray" 
                    value="{{c.id}}">{{c.name}}</option>
                  </select> 
                </div>
              </div>

              <div class="form-group">
                <label for="moduleId" class="col-sm-2 control-label">Cars</label>
                <div class="col-sm-10">
                  <select id='moduleId'>
                    <option *ngFor="let m of filteredCarsModule" 
                    value="{{m.id}}">{{m.name}}</option>
                  </select> 
                </div>
              </div>

Within the TypeScript file: filteredCarsModule:{ id: number, carId:number ,name: string }[];

   carsArray: { id: number, name: string }[] = [
    { "id": 1, "name": "Car1" },
    { "id": 17, "name": "Car2" },
    { "id": 3, "name": "Car3" }
  ];

  carModulesArray:{ id: number, carId:number ,name: string }[] = [
    { "id": 1, "carId":1, "name": "Module1" },
    { "id": 2, "carId":1, "name": "Module2" },
    { "id": 3, "carId":1,"name": "Module3" },
    { "id": 4, "carId":17,"name": "Module4" },
    { "id": 5, "carId":3,"name": "Module5" }
  ];


  ngOnInit() {
    this.filteredCarsModule = this.getCarsModuleByType(1);
  }

  onCarsChange(carValue) {
    this.filteredCarsModule = this.getCarsModuleByType(carValue.target.value);
  }

  getCarsModuleByType(carValue):{ id: number, carId:number ,name: string }[]
  {
    return this.carModulesArray.filter(module=>module.carId==carValue);
  }

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

Displaying error messages in Angular Material upon clicking a button

I am struggling with validation using the <mat-form-field> and <mat-error>. The validation works as expected when the user tabs out of the input without filling it. However, I'm facing a challenge in making this error show up when a button ...

Tips on transferring a child Interface to a parent class

Here is my code snippet: LocationController.ts import {GenericController} from './_genericController'; interface Response { id : number, code: string, name: string, type: string, long: number, lat: number } const fields ...

The sliding hamburger menu children fail to move in unison with the parent

I'm currently working on a dynamic sliding navigation menu that activates when the hamburger icon is clicked. However, I am facing an issue where the child <a> elements are not sliding along with the parent div. You can see how it currently loo ...

Utilizing web components in React by solely relying on a CDN for integration

I have a client who has provided us with a vast library of UI elements that they want incorporated into our project. These elements are stored in javascript and css files on a CDN, and unfortunately I do not have access to the source code. All I have at my ...

When attempting to open a form in edit mode, data binding fails to work across multiple form controls

When clicking on the edit button, data is loaded into the form using [(ng-model)], however, it seems to be working correctly only for some fields and not all fields. The data is displayed in only a few fields despite receiving data for all fields. Below is ...

You cannot use ca.select(....).from function after the code has been minified

My Angular application utilizes squel.js and functions correctly in development mode. However, upon building the app for production and attempting to use it, I encounter the following error message: ca.select(...).from is not a function This error ref ...

Use the constant INLINE with npm commands to specify inline behavior

Today I was working on Angular2 using the template provided at . Following the installation guide, I executed the commands as instructed. I have successfully installed Node.js v6.9.1. npm install --Executed without any issues. npm server --Encountered a ...

Converting an array of objects to an array of JSON objects in TypeScript

My dilemma lies in the data I have uploaded under the _attachments variable: https://i.sstatic.net/jnFNH.png My aim is to format this data for insertion in the following structure: "_attachments": [ { "container": "string", "fileName": "string" ...

Button with circular icon in Ionic 4 placed outside of the toolbar or ion-buttons

Is it possible to create a circular, clear icon-only button without using ion-buttons? I am trying to achieve the same style as an icon-only button within ion-buttons (clear and circular). Here is my current code: <ion-button icon-only shape="round" co ...

Creating a dropdown menu in Bootstrap 5 without using any of the Bootstrap

In my Angular application, I have a header with icons and pictures that I would like to use as dropdown menus. The code snippet for this functionality is shown below: <li class="nav-item dropdown"> <a class="nav-li ...

Angular2 and ES6 Promise in JavaScript - tackling the issue of undefined variables

I am working with an array of objects like the one shown below: let PAGES = [ new BasePage( 'home', 'test') ]; let pagesPromise = Promise.resolve(PAGES); My goal is to retrieve a BasePage object by calling the following met ...

Issue encountered when importing a font in TypeScript due to an error in the link tag's crossorigin

How do I troubleshoot a TypeScript error when importing a custom font, such as a Google font? <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> Below is the specific error message: Type 'boolean' is ...

Error: A variable is potentially 'undefined' (ts2532), even though I have just assigned a value to it

Encountering Object is possibly 'undefined'. ts(2532) errors in TypeScript for an optional parameter, despite being clearly defined... interface Foo { keyValue?: Record<string, string> } const a: Foo = { keyValue: { key1: 'value&apo ...

The Angular Button fails to display when all input conditions are met

I'm currently working on validating a form using this link. The requirement is simple - when an input field is invalid, the `save` button should be disabled. Conversely, when all input fields are valid, the `SAVE` button should be enabled/shown. The & ...

I encountered difficulties accessing the native Camera API when working with the most recent version of Ionic

Every time I try to run $ ionic cordova plugin add @ionic-enterprise/camera I encounter the following error message [OK] Integration cordova added! ✔ Creating ./www directory for you - done! > cordova plugin add @ionic-enterprise/camera You have ...

Utilizing Sequelize's Where clause with the flexibility of optional parameters

Can you guide me on writing Sequelize queries with optional parameters? Consider the below query example: const result : SomeModel[] = await SomeModel.findAll( {where: { id: givenId, ...

How can you generate a "Package Contains Lower Node Version" error message during the installation of an NPM package if the node version is higher than the current system's node version?

I am looking for a way to trigger an error during the installation of an NPM package if the node version supported by that module does not match the system/server node version. Specifically, I want to prevent the installation of any npm module that suppor ...

Book of Tales displaying Emotion Styling upon initial load only

I'm currently working with the styled api provided by emotion in order to create a custom styled button. const StyledButton = styled(Button)` background-color: ${theme.palette.grey['800']}; width: 50; height: 50; &:hover { ba ...

When comparing the values of two arrays with undefined property values

Struggling with sorting an array of arrays that works perfectly except when the property value is undefined. Take this example: posts array = {id: "1", content: "test", "likes":[{"user_id":"2","user_name":"test"}] }, {id: "2", content: "test", "likes": ...

Content of reusable angular form is not visible on the homepage

I am currently working on creating a reusable Angular form within an Ionic application. Despite following various tutorials and Stack Overflow posts, I have resolved all errors but unfortunately, the content does not display on the parent page. Here is my ...