DaFoot
DaFoot

Reputation: 1567

How can I make mat-select show appropriate option?

I have a mat-table that renders a collection of 'Competitor'. I am trying to add a mat-select that allows users to select which event a competitor is attending.

Angular: 10.1.3

Angular material: 10.2.2

So far I have this...

<mat-cell class="number-column" *matCellDef="let competitor">
      <mat-form-field>

        <!-- TODO Remove this debug -->
        {{competitor.eventId}}

        <mat-select [(ngModel)]="competitor.eventId"
                    (selectionChange)="updateCompetitorWithEvent(competitor, $event.value)">
          <mat-option *ngFor="let event of events" [value]="event.id">
                      {{event.name}}
          </mat-option>
        </mat-select>
      </mat-form-field>
    </mat-cell>

The debug statement outputting the competitor.eventId is updated as I expect. This happens via the selectionChange event handler (which also persists the change in the backend - this also works correctly).

My problem is that although the data appears correct when fetched from / sent to the backend, the mat-select does not update the input to match the id provided in competitor.eventId.

If it helps explain what I'm trying to achieve....

        <mat-select [(ngModel)]="competitor.gradingId"
                    (selectionChange)="updateCompetitorWithGrading(competitor, $event.value)">
          <mat-option *ngFor="let event of events"
                      [value]="event.id"
                      [selected]="competitor.eventId==event.id">
            {{event.id}}:{{event.name}}
          </mat-option>
        </mat-select>

Of course [selected] doesn't exist on mat-option, but hopefully, that explains what I want to achieve.

Upvotes: 0

Views: 125

Answers (1)

DaFoot
DaFoot

Reputation: 1567

I ended up with code below which appears to work. I'm not so sure this is the correct Angular best practice way of doing this it seems to work....

    <mat-select value="{{competitor.eventId}}"
                    (selectionChange)="updateCompetitorWithGrading(competitor, $event.value)">
          <mat-option *ngFor="let event of events"
                      [value]="event.id">
            {{event.id}}:{{event.name}}
          </mat-option>
        </mat-select>

This is the bit that fixed it...

value="{{competitor.eventId}}"

Upvotes: 0

Related Questions