I am encountering an issue with my mat-select
and mat-option
control.
I am trying to apply the selected attribute to the first mat-option
control without using binding on [(ngModel)]
or [(value)]
.
The mat-option
control is being generated by the *ngFor
directive, but I want to avoid needing a property in my component that typically binds the mat-select
UI control with [(ngModel)]
.
I have tried various approaches:
<mat-form-field>
<mat-label>Currency</mat-label>
<mat-select #currencySelect>
<mat-option *ngFor="let currency of currencies; let isFirst = first" [value]="currency" [attr.selected]="isFirst ? 'selected' : null">
{{currency | currencyName}}
</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-label>Currency</mat-label>
<mat-select #currencySelect>
<div *ngFor="let currency of currencies; let isFirst = first">
<mat-option *ngIf="isFirst" selected [value]="currency">
{{currency | currencyName}}
</mat-option>
<mat-option *ngIf="!isFirst" [value]="currency">
{{currency | currencyName}}
</mat-option>
</div>
</mat-select>
</mat-form-field>
Out of these attempts, only the following achieved the desired outcome:
<mat-form-field>
<mat-label>Currency</mat-label>
<mat-select #currencySelect [value]="currencies != null && currencies.length != 0 ? currencies[0] : null">
<mat-option *ngFor="let currency of currencies;" [value]="currency">
{{currency | currencyName}}
</mat-option>
</mat-select>
</mat-form-field>
However, this solution relies on binding the [value]
, which is not ideal for me.
I would prefer the code structure to be like this:
<mat-form-field>
<mat-label>Currency</mat-label>
<mat-select #currencySelect>
<mat-option *ngFor="let currency of currencies; let isFirst = first" [value]="currency" [selected]="isFirst">
{{currency | currencyName}}
</mat-option>
</mat-select>
</mat-form-field>
How can I achieve this?
I wish to accomplish it without the need for a component property that tracks the selected item. Thank you.