tonyf
tonyf

Reputation: 35539

Two way Binding in Angular using Select List

I wish to set up two-way binding in Angular v5, specifically using an Angular Material select list.

I basically have the following sample code which is a snippet from a HTML table and assume when rendered on the screen, only two rows will appear, i.e.:

<tr *ngFor="let currentHero of currentHeroes; let in = index-{{in}}">
  <td>
    <mat-form-field>
      <mat-select [(ngModel)]="currentHero.product" name="product">
        <mat-option *ngFor="let product of products" [value]="product">
          {{product}}
        </mat-option>
      </mat-select>
    </mat-form-field>                            
  </td>
</tr>

With the code above, which displays two select drop-down lists over two rows, what I would like to achieve and unsure how to do, is that when the user makes a Product selection from the first select drop-down list on row 1, I would like the same product selection to be reflected in the second select drop-down list on row 2.

I basically want the first select list to also control the second select list, i.e. if I chose "Toaster", then this "Toaster" was also set on row 2 select list.

This is the design that I need to keep with.

Upvotes: 0

Views: 5580

Answers (1)

bugs
bugs

Reputation: 15313

You need to use [(value)]="..." on your select element to have two-way binding.

<mat-form-field>
  <mat-select [(value)]="selected">
    <mat-option>None</mat-option>
    <mat-option value="option1">Option 1</mat-option>
    <mat-option value="option2">Option 2</mat-option>
    <mat-option value="option3">Option 3</mat-option>
  </mat-select>
</mat-form-field>

<mat-form-field>
  <mat-select [(value)]="selected">
    <mat-option>None</mat-option>
    <mat-option value="option1">Option 1</mat-option>
    <mat-option value="option2">Option 2</mat-option>
    <mat-option value="option3">Option 3</mat-option>
  </mat-select>
</mat-form-field>

This way, any selection in one of the elements will be reflected in the other one (demo).

Upvotes: 3

Related Questions