0
votes

I am trying to use a simple select dropdown which should be having a default option selected. I tried using ngValue, selected, [selected]="true" but none of them work.

<select class="form-control" [(ngModel)]="keyType"> 
<option [ngValue]="'Numeric'" selected>Numeric</option>
  <option [ngValue]="'Random'">Random</option>
</select>

It shows as blank initially, but when I choose any option, there's no blank option anymore. I can't make changes on the TS side, because keytype is always '', unless a certain condition is met.

Stackblitz link: https://stackblitz.com/edit/angular-zhtkiv?file=src%2Fapp%2Fapp.component.html

3
<option></option> does providing an empty option in html , causes any problem to your requirement? stackblitz.com/edit/angular-suxlrd?file=src/app/… - Ampati Hareesh
@AmpatiHareesh, no, but I don't see the point of doing it. - Aijaz
Initially it shows empty , because keyType does not have any value in it, once after the selection, keyType equals Numeric/Random..and here you are not providing the empty value, so that keyType goes to '' ,That's the reason you can't see the empty value once after the selection - Ampati Hareesh

3 Answers

0
votes

Here is your blitz

You have to set the value of your ngModel to the corresponding option you want selected.

And blank values need to be explicitly written as an option, otherwise they disappear once you chose a value. That's not Angular, that's HTML standards.

0
votes

Try using the binding like this, no need for selected and ngValue

import { Component, OnInit } from '@angular/core';

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit  {
    keyType: any;
    items = ['Numeric', 'Random']

    ngOnInit(){
        this.keyType = this.items[0];
    }
}

And for the html

<select class="form-control" [(ngModel)]="keyType">
<option *ngFor="let i of items" [value]="i">{{i}}</option>  
</select>

{{keyType}}
0
votes

One way of doing is by providing default option with empty value

Here is the modified stackblitz:https://stackblitz.com/edit/angular-suxlrd?file=src/app/app.component.html