Search code examples
angularangular8ngx-select-dropdown

Auto select value in dropdown


How do I set a value as the default selected value in the dropdown? I am using angular 8. I have the following html

<div class="form-group">
        <label class="form-control-label col-form-label-sm">Content Type</label>
        <select class="form-control form-control-sm" [(ngModel)]="item.contentType"  formControlName="contentType" name="contentType">
          <option   *ngFor="let contentType of contentTypes" [value]="contentType.name" >{{contentType.displayName}}</option>
        </select>
      </div>

I have tried using [selected]="contentType.name=='TEXT'" but the dropdown still does not show the default selected value as "Text Only".

<div class="form-group">
        <label class="form-control-label col-form-label-sm">Content Type</label>
        <select class="form-control form-control-sm" [(ngModel)]="item.contentType" formControlName="contentType" name="contentType">
          <option *ngFor="let contentType of contentTypes" [value]="contentType.name" [selected]="contentType.name=='TEXT'">{{contentType.displayName}}</option>
        </select>
      </div>

contentTypes is an array of [{"name":"TEXT","displayName":"Text Only"},{"name":"AUDIO","displayName":"Audio"},{"name":"VIDEO","displayName":"Video"}]


Solution

  • Karu,

    by default item.contentType should being inited with value coresponding with some option from your list of contentTypes. If you init item.contentType with value TEXT for example, option with value TEXT will be preselected by default.

    Or, you can just put option with null value with text Select content (for example). And validate it, if it should be required. Something like:

    <div class="form-group">
       <label class="form-control-label col-form-label-sm">Content Type</label>
       <select class="form-control form-control-sm" [(ngModel)]="item.contentType"
             name="contentType">
          <option [value]="null">Select content</option>
          <option *ngFor="let contentType of contentTypes" [value]="contentType.name"> 
              {{contentType.displayName}}
          </option>
        </select> 
    </div>
    

    Anyway, deside which approach for building form you will use (Reactive forms or Template driven forms). Because you did a mistake in definition for select component. Use only [(ngModel)] definition and remove formControlName="contentType", if you would like to use template driven forms pattern. Study this first in link provided.