material-components / material-web

Material Design Web Components
https://material-web.dev
Apache License 2.0
8.93k stars 840 forks source link

md-select-option selected not getting selected on angular reactive form #5590

Open asegurala opened 2 months ago

asegurala commented 2 months ago

What is affected?

Component

Description

When I try to use md-outlined-select with Reactive Forms on Angular 17

Reproduction

In Angular, I have a form with Reactive Forms, it has a couple of Inputs, Selects, and a Submit button to perform a search. When navigating to another route and returning to my search page, the input fields do show the previously entered values, but this does not happen with the Selects.

However, if I use the Selects with ngModel using Template-driven forms, all the select fields work correctly.

Selects doesn't works with Reactive Forms on Angular 17.x:

<form (ngSubmit)="onSubmit()" [formGroup]="form" class="row middle p-24 hide-down-md">

<md-outlined-text-field formControlName="term" ngDefaultControl placeholder="Club"></md-outlined-text-field>
<!--SPORT-->
<md-outlined-select formControlName="sportId" ngDefaultControl>
  <md-select-option *ngIf="!sport" disabled value="">
    <div slot="headline" selected>Deporte</div>
  </md-select-option>
  @for (sport of (sports$ | async); track sport.id) {
    <md-select-option value="{{sport.id}}">
      <div slot="headline">{{ sport.name }}</div>
    </md-select-option>
  }
</md-outlined-select>

Workaround

Using Template-drive Forms works:

<md-outlined-select [(ngModel)]="sportId" ngDefaultControl> <md-select-option *ngIf="!sport" disabled value="">

Deporte
</md-select-option>
@for (sport of (sports$ | async); track sport.id) {
  <md-select-option value="{{sport.id}}">
    <div slot="headline">{{ sport.name }}</div>
  </md-select-option>
}

Is this a regression?

No or unsure. This never worked, or I haven't tried before.

Affected versions

@material/web@1.4.x / and nightly

Browser/OS/Node environment

Brave Version 1.64.122 Chromium: 123.0.6312.122 (Official Build) (64-bit) Chrome / Firefox on Arch Linux 6.8

Node 18.18.2 Angular 17.0

austinw-fineart commented 2 months ago

In my case, the issue appears to be caused by dynamically populating md-select-option(s) causing the select to appear blank even though the option is selected when you open the menu. The weird thing though is that sometimes the select is blank and sometimes the select isn't blank.

Vyachean commented 2 months ago

I was able to reproduce this without frameworks. @austinw-fineart guess is correct. the problem is not specific to Angular, I got the problem when working with Vue.

davie-robertson commented 1 month ago

I also had a similar issue when setting the selected value without any framework, discord discussion and workaround here