Angular 8 : Set default selected value for select tag
24,538
Solution 1
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.
Solution 2
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>
Author by
547n00n
Updated on November 18, 2020Comments
-
547n00n over 3 years
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);