'How to default a value in select tag while using ngModel in Angular 6?
I have this below code in Angular 6:
<select class="form-control form-control-sm" #ig="ngModel" [(ngModel)]="assetFormDetails.ig">
<option value="" >Select Ig</option>
<option *ngFor="let ig of igList" value="{{ig.igName}}">{{ig.igName}}</option>
</select>
When I am getting the value of assetFormDetails.ig as '' or null , it is not selecting the node <option value="" >Select Ig</option> . Instead it is creating and selecting a new blank node on the drop-down list.
How can I make it select this node: <option value="" >Select Ig</option> in this case.
Solution 1:[1]
simply just give a assetFormDetails.ig a intial value
as example
<select class="form-control" #ig="ngModel" [(ngModel)]="assetFormDetails.ig">
<option value="" >Select Ig</option>
<option *ngFor="let ig of [1,2,3,4,5]" value="{{ig}}">{{ig}}</option>
</select>
component
assetFormDetails = {ig:"3"}; // assetFormDetails = {ig:""} Select Ig
Solution 2:[2]
I just added name attribute to the select tag, it just worked fine. like name="ig"
<select class="form-control" name="ig" #ig="ngModel" [(ngModel)]="assetFormDetails.ig">
<option value="" >Select Ig</option>
<option *ngFor="let ig of [1,2,3,4,5]" value="{{ig}}">{{ig}}</option>
</select>
I am not sure, but it seems "name" attribute is required in a template driven form.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Muhammed Albarmavi |
| Solution 2 | Dibyajyoti Behera |
