angularhtml-selectangular2-ngmodel

Angular select option with selected attribute not working


Using Angular 4, I have a html template and I want a selection box with two options. One of those options should be pre-selected by default.

<select name="rate" #rate="ngModel" ngModel required>
    <option selected value="hr">hr</option>
    <option value="yr">yr</option>
</select>

Details:

I assign #rate="ngModel" so that I can reference the value somewhere else in the template, in a conditional statement or with interpolation {{rate.value}}. For that to work I simply add ngModel to the tag. I'm not binding to anything in the component class as this control is only used to provide it's value to another control in the same template.

Issue:

In Chrome, and Microsoft Edge, the box is empty, no default value selected. If I get rid of #rate="ngModel" ngModel it works. However, I need the reference to rate.value.

I tried various combinations of ngValue, value, [ngValue], [value], but I'm not trying to bind the value to a model and I'm not using a ngFor loop. There is no further styling on the select box either.


Solution

  • If you don't wish to have a two-way binding, you can set ngModel to the 'default' value and with the template local variable get the selected value:

    <select #rate ngModel="hr">
        <option selected value="hr">hr</option>
        <option value="yr">yr</option>
    </select>
    
    <p *ngIf="rate.value == 'hr'">hr</p> 
    <p *ngIf="rate.value == 'yr'">yr</p>
    
    {{rate.value}}
    

    DEMO