plkpiotr
plkpiotr

Reputation: 374

Select dependent on another select - Material Angular

I would like to create two mat-selects. One of them (related with reference) is dependent on the select with type.

types is an array with enums implemented in Typescript.

I tried as follows, but after choice on of the references which were correct after change type, the select with reference is empty...

<mat-form-field>
  <mat-label>Type</mat-label>
  <mat-select placeholder="Type" formControlName="type" name="type">
    <mat-option>None</mat-option>
    <mat-option *ngFor="let t of types" [value]="t">
      {{t}}
    </mat-option>
  </mat-select>
</mat-form-field>

<mat-form-field>
  <mat-label>Reference</mat-label>
  <mat-select placeholder="Reference" formControlName="reference" name="reference">
    <div [ngSwitch]="type.value">
      <div *ngSwitchCase="types[0]">
        <mat-option *ngFor="let r of deliveries" [value]="r.id">
          {{r.id}}
        </mat-option>
      </div>
      <div *ngSwitchCase="types[1]">
        <mat-option *ngFor="let r of orders" [value]="r.id">
          {{r.id}}
        </mat-option>
      </div>
      <div *ngSwitchDefault>
        <mat-option>None</mat-option>
      </div>
    </div>
  </mat-select>
</mat-form-field>

Could someone please assist? Maybe, there's a better way of doing it?

By the way... Creating new object without "select with reference" is correct, so probably the logic of this select is guilty...

Upvotes: 3

Views: 3219

Answers (1)

Eliseo
Eliseo

Reputation: 57939

there're several ways to achaive this. You can, e.g. create two array of array

deliveries=[[1,2,3],[4,5],[6,7,8]]
orders=[["A","B","C"],["D","E"],["F","G","H"]]

and make the

<mat-option *ngFor let r of deliveries[myForm.get('type').value]>...</mat-option>
 //and
<mat-option *ngFor let r of orders[myForm.get('type').value]>...</mat-option>

Upvotes: 1

Related Questions