How to Preselect value using Datalist Dropdown in Angular?

466 Views Asked by At

I have an editable dropdown in which I need to autopopulate its default value from a template. The default value is fetched from "this.Model.Application.environment" that has "dev" as a value. The below code gives me a editable dropdown but I need to preselect the value from the template. The [(ngModel)]="this.Model.Application.environment" in is showing the default value("dev") on the page, but it does not show the other drop down values("qa/prod) and also its not editable. so I removed ngModel from tag. Please help me how to crack it. The requirement is 1.editable dropdown, 2.preselect the value, 3.show other values in the dropdown. (1 & 3 is working now)

<div class="select-editable">
   <input list="envVal" id="environment" name="environment" #select class="form-control"                              placeholder="Select Base Image Version" size="medium"                             style="width:326px; padding-top:5px;max-width: 100%;" (change)='updatebaseimageversion($event)' />
      <datalist id="envVal" [(ngModel)]="this.fmGeneratorModel.Application.environment">
         <ng-container *ngFor="let env of environmentList">
            <option [ngValue]="env" [selected]="env === 'dev'" >{{env}}</option>
         </ng-container>
      </datalist>
</div>
1

There are 1 best solutions below

5
On BEST ANSWER

You have to use [(ngModel)] only with input elements. In your example it used with datalist - that's wrong.

Simple working example:

<label for="browser">Choose your browser from the list:</label>
  <input list="browsers" name="browser" [(ngModel)]="model" #browser>
  <datalist id="browsers">
    <option value="Edge">
    <option value="Firefox">
   ...
  </datalist>