Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle Angular 5 select binding to a null value

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.

like image 566
dfmetro Avatar asked Feb 01 '18 09:02

dfmetro


1 Answers

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>
like image 121
Alec Gerona Avatar answered Jan 01 '23 21:01

Alec Gerona