A
A
Artur Zagorsky2019-10-30 14:42:41
JavaScript
Artur Zagorsky, 2019-10-30 14:42:41

How to make a select display options depending on the selected option of the neighboring select?

Here is the structure:

<div class="filter">
      Filter by:
      <nb-select placeholder="Default" status="danger">
        <nb-option *ngFor="let criterion of filterConfig | keyvalue" [value]="criterion.key">{{criterion.key}}</nb-option>
      </nb-select>
      <nb-select placeholder="Default" status="danger">
        <nb-option *ngFor="let option of filterConfig | keyvalue" [value]="option.value">{{option.value}}</nb-option>
      </nb-select>
</div>

The keys filterConfigare the elements of the first select, and the values ​​are the elements of the second.
filterConfig = {
    default: [...],
    contractStatus: [...],
    contractType: [...],
    userId: [...]
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrew, 2019-10-30
@KickeRockK

<div class="filter">
      Filter by:
<div *ngFor="let criterion of filterConfig | keyvalue">
      <nb-select placeholder="Default" status="danger">
        <nb-option  [value]="criterion.key">{{criterion.key}}</nb-option>
      </nb-select>
      <nb-select placeholder="Default" status="danger">
        <nb-option [value]="criterion.value">{{criterion.value}}</nb-option>
      </nb-select>
</div>
</div>

A
Anton Shvets, 2019-10-30
@Xuxicheta

<select #optSelect (change)="kindSelect.kinds = filterConfig[optSelect.value]">
  <option *ngFor="let opt of filterConfig | keyvalue">{{opt.key}}</option>
</select>

<select #kindSelect>
  <option *ngFor="let kind of (kindSelect.kinds || filterConfig.fruit)">{{kind}}</option>
</select>

public filterConfig = {
  fruit: ['apple', 'orange', 'pineapple', 'grape'],
  vegetable: ['carrot', 'potato', 'dill', 'cucumber']
}

The intermediate variable kindSelect.kindswas introduced due to the fact that if you simply take optSelect.valuethe value on the initial rendering of the template, value does not yet optSelect.valueappear on the first change detection, and in the dev mode on the second detection pass, value mismatches with the template are detected, which will cause ExpressionChangedAfterItHasBeenCheckedError.
Tip: do not get carried away with such shamanism, but make a normal reactive form and subscribe to it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question