I'm facing the issue to preselect an entry in a dynamic populated dropdown.
It's about a filed for choosing a language. The possible languages are populated dynamically. I want to have a preselected value as a hint, which is not included in this list. Eg "Choose language"
Here is my code what I thougt it might work:
<select id="languageSelection" class="form-control" [(ngModel)]="selectedLanguage" (ngModelChange)="onLanguageChange($event)">
<option selected disabled hidden>Choose language</option>
<option class="" *ngFor="let l of languages" [ngValue]="l">{{l}}</option>
</select>
I get the list of the languages, but there is a language preselected. If I remove the "hidden"-tag the "Choose language" appears grayed out in the list. But a language is preselected, too.
Thank you in advance!
[(ngModel)]
is overriding the selected attribute. A workaround would be to set a predefined value to your variable selectedLanguage
, and use that in the options as default value, so for example:
TS:
selectedLanguage = 0;
HTML:
<select id="languageSelection" class="form-control" [(ngModel)]="selectedLanguage" (ngModelChange)="onLanguageChange($event)">
<option [disabled]="true" value="0">Choose Language</option>
<option class="" *ngFor="let l of languages" [ngValue]="l">{{l}}</option>
</select>
That should do it :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.