Search code examples
angularangular-forms

Angular7 Use selected option in a select to set the options in another select


I have the following two select elements in my Angular 7 project:

enter image description here

My requirement is to populate the elements in the second select based on the value selected from the first select.
I have tried the following so far:

  1. Used ngModel directive to get the the first selected value
  2. Use the selected value to populate the items in the second the select element.

This is the code:
app.component.html:

    <mat-form-field>
    <mat-label>Select Master Bot</mat-label>
    <mat-select [(ngModel)]="selectedMasterBot">
    <mat-option *ngFor="let masterBot of masterBotList" 
    [value]="masterBot.value">{{ masterBot.view }}</mat-option></mat-select> 
    </mat-form-field>&nbsp;
    <mat-form-field>
    <mat-label>Select UseCase</mat-label>
    <mat-select [(ngModel)]="selectedUseCase">
    <mat-option *ngFor="let useCase of 
    masterBotUseCaseMapping.selectedMasterBot" [value]="useCase.value">{{ 
    useCase.view}}
    </mat-option>
    </mat-select>
    </mat-form-field>
    <button mat-button (click)="print()">Click me</button>  

app.component.ts:


    public selectedMasterBot;
    public selectedUseCase;

    public masterBotUseCaseMapping = {
    "select1Value": [
    {
    "view": "incomprehension",
    "value": "incomprehensionID"
    },
    {
    "view": "greetings",
    "value": "greetingsID"
    }
    ], "select2Value": [
    {
    "view": "incomprehension",
    "value": "incomprehensionID"
    }
    ]
    }

    public masterBotList = [{
    view: 'select1',
    value: 'select1Value'
    },
    { 
    view: 'select2',
    value: 'select2Value'
    }]

Solution

  • A simple use of ngModel can solve your problem of cascaded dropdown

    Demo at https://stackblitz.com/edit/angular-cascaded-dropdown

    It looks like the mapping in your data is incorrect which you need to fix

    Update fiddle https://stackblitz.com/edit/angular-wteh9o to support your data structure.

    THe main issue here is that you are trying to access the property value ising dot notation whereas you should be using array notation as

    <mat-option *ngFor="let useCase of 
    masterBotUseCaseMapping[selectedMasterBot]" [value]="useCase.value">