Set default select list value Angular2

Issue

I want to set the default option for the select in angular 2 as “Select an option”. Here is the code that I have so far:

HTML

<div class="form-group">
                        <label class="col-md-4 control-label" for="CustomFix">Select an option:</label>
                        <div class="col-md-4">
                            <select id="example" name="example" class="form-control" [(ngModel)]="exampleArray" (ngModelChange)="changes()">
                                <option disabled selected>Select a Custom Fix</option>
                                <option *ngFor="let example of exampleArray" [ngValue]="example">{{example.attribute }}</option>
                            </select>
                        </div>
                    </div>

Typescript

changes(){
console.log(this.example.option);
}

I have the line in my html:

<option disabled selected>Select a Custom Fix</option>

How can I enable this as the default option? It is separate from my array used with ngModel

Solution

If you use [ngValue] then you need to assign the identical object instance to exampleArray. Another object instance with the same properties and values won’t do.

If you use [value]="..." instead of [ngValue], then only strings can be used and for string comparison to different string instances containing the same characters are considered equal, but that’s not the case for object instances where exampleArray needs to reference the exact same object reference used with [ngValue].

Actually

[(ngModel)]="exampleArray"

in your example is invalid, because the model should not be the array that is used to generate the <option> elements, it should be a property that holds the selected value.

   <div class="form-group">
        <label class="col-md-4 control-label" for="CustomFix">Select an option:</label>
        <div class="col-md-4">
            <select id="example" name="example" class="form-control" [(ngModel)]="selectedItem" (ngModelChange)="changes()">
                <option disabled selected>Select a Custom Fix</option>
                <option *ngFor="let example of exampleArray" [ngValue]="example">{{example.attribute }}</option>
            </select>
        </div>
    </div>
constructor() {
  this.selectedItem = exampleArray[1]; // will make the 2nd element of `exampleArray` the selected item
}

Answered By – Günter Zöchbauer

Answer Checked By – Pedro (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.