1

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"];
1
  • 1
    Does giving a value to statusValueToSet beforehand not help? Commented Jul 19, 2016 at 10:02

1 Answer 1

3

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 = "";
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much. The problem is now, that the initial value 'default' is already a valid form. Any idea for a quick fix?
I think I found something - just using an empty string as value seems to invalidate it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.