Johannes
Johannes

Reputation: 2812

Set the default value for an HTML <select> element in angular2

How can I set the default value for an HTML element in angular2? The simplest way to go would be my following attempt. This does not work yet, could somebody help me please?

// extract from template
<div class="form-group">
  <label for="status">Status: </label>
  <select class="form-control" name="status" #status="ngModel" [(ngModel)]="statusValueToSet" required>
    <option selected disabled>Choose here</option>
    <option *ngFor="let status of statuses" [value]="status">{{status}}
    </option>
  </select>
</div>

// in the component class  
statuses:string[] = ["New", "Accepted", "Invalid"];

Upvotes: 1

Views: 3706

Answers (1)

Maximilian Riegler
Maximilian Riegler

Reputation: 23506

Just initialize statusValueToSet in your class body, but leave the Choose here option in the select:

// extract from template
<div class="form-group">
  <label for="status">Status: </label>
  <select class="form-control" name="status" #status="ngModel" [(ngModel)]="statusValueToSet" required>
    <option [value]="''">Choose here</option>
    <option *ngFor="let status of statuses" [value]="status">{{status}}
    </option>
  </select>
</div>

statuses: string[] = ["New", "Accepted", "Invalid"];
statusValueToSet: string = "";

Upvotes: 3

Related Questions