3

I'm using a mat-select within a table (so each row has one) that will be shown when the row is selected for editing.

The mat-select has an *ngIf on it to hide it when not in edit mode. It is also populated by a key/value map within the component. The values are received and set during the ngOnInit lifecycle hook. The mat-select is also NOT in a form.

When I select edit mode, the mat-select appears but it displays the blank option, forcing users to reselect the option already applied to the row. I can confirm that they keys and values are correctly set, and the object value for the typeId is also set.

I've tried several things I found on stack overflow but so far none have worked. (e.g. using the selected attribute, using [(value)] on mat-select, and attempting to write a method to set it when appearing).

How can I display the mat-select with the *ngIf and have the current value be shown by default?

HTML

<ng-container [matColumnDef]="myColumn">
    <th mat-header-cell *matHeaderCellDef mat-sort-header>Column 1</th>
    <td mat-cell *matCellDef="let object">
        <mat-form-field *ngIf="object.edit">
            <mat-select #objectTypeId="ngModel"
                        placeholder="Type"
                        disableOptionCentering
                        [(ngModel)]="object.objectTypeId"
                        [(value)]="object.objectTypeId"
                        required>
                <mat-option *ngFor="let objectType of objectTypeSelectViewModel?.map | keyvalue" value="{{objectType?.key}}">
                    {{objectType?.value}}
                </mat-option>
            </mat-select>
        </mat-form-field>
        <span *ngIf="!object.edit">{{object?.objectType}}</span>
    </td>
</ng-container>
expenguin
  • 1,052
  • 2
  • 21
  • 42

0 Answers0