3
votes

I want to set a default option value for select tag, the values are declared as table in my component and showed with ngFor directive :

<form>
    <div class="form-group col-4">
      <span class="badge badge-theme mb-3">Quantité</span>
      <select class="form-control" id="exampleFormControlSelect1">
        <option *ngFor="let quantity of Quantities" [ngValue]="quantity">{{quantity}}</option>
      </select>
    </div>
    <div class="form-group col-4">
      <span class="badge badge-theme mb-3">Message personnalisé</span>
      <textarea class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea>
    </div>
  </form>

components.ts

  Quantities = Array(50).fill(0).map((x,i)=>i);
2
your select is getting populated with values and you are unable to set default value, is that right? - Plochie
yes that's it @PareshLomate - sahnoun

2 Answers

5
votes

You can do it the following way:

component.html

 <select [(ngModel)]="seletedValue" class="form-control" id="exampleFormControlSelect1">
        <option *ngFor="let quantity of Quantities" [ngValue]="quantity">{{quantity}}</option>
 </select>

component.ts

seletedValue = ''; // set some default value from Quantities

OR

component.html

 <select [(ngModel)]="seletedValue" class="form-control" id="exampleFormControlSelect1">
        <option value="" [disabled]="true">Select quantity</option>
        <option *ngFor="let quantity of Quantities" [ngValue]="quantity">{{quantity}}</option>
 </select>
4
votes

I have created Stackblitz.

What I did is created a variable in compoent and then bonded it with select tag. [(ngModel)]="selectedValue".

The variable then can be used as per your logic.