I have a reactive form with a select
<select [(ngModel)]="user.positionId" name="positionId" class="custom-select form-control form-control-sm" required
formControlName="positionId"
[ngClass]="{
'is-invalid': positionId.invalid && (positionId.dirty || positionId.touched),
'is-valid': positionId.valid && (positionId.dirty || positionId.touched)
}">
<option value="">--Select--</option>
<option *ngFor="let position of user.positionSelectList" value="{{position.value}}">
{{position.text}}
</option>
</select>
It gets passed positionId which is a nullable number
export class User{
id: string;
userName: string;
positionId?: number;
}
The above works when I pass a number value as positionId.
However when it gets passed a null value then the default option of "--Select--" is not selected but an additional blank option appears above it.
What I have tried.
<option value=null>--Select--</option>
and
<option value=udefined>--Select--</option>
but this gives the same result of "--Select--" not selected
I do not wish to set hardcoded number values a fixed number e.g. -1 as I need the required validation to kick in which requires a blank value if not selected.
Have you tried using ngValue
?
<select [(ngModel)]="user.positionId" name="positionId" class="custom-select form-control form-control-sm" required
formControlName="positionId"
[ngClass]="{
'is-invalid': positionId.invalid && (positionId.dirty || positionId.touched),
'is-valid': positionId.valid && (positionId.dirty || positionId.touched)
}">
<option [ngValue]="null">--Select--</option>
<option *ngFor="let position of user.positionSelectList" value="{{position.value}}">
{{position.text}}
</option>
</select>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With