I have simple component that contains only form:
import {Component, FORM_DIRECTIVES, NgFor} from \'angular2/angular2\';
@Component({
selector: \'test-com
I got this to work by doing the following:
enter code here
<div class="form-group">
<label for="metricsType">metrics type</label>
<select id="metricsType" class="form-control" required [(ngModel)] ="model.metrics.type">
<option value="" disabled="true" [selected]="!model.metrics.type">--please select--</option>
<option *ngFor="let item of metricTypes" [value]="item.value">{{item.label}}</option>
</select>
</div>
then using css ng-pristine for styling
select {
border: 1px solid transparent;
&.ng-pristine{
font-style: italic;
color: darken($white, 50%);
}
}
<select class = "form-control"name="searchByRegion" [(ngModel)] = searchByRegion>
<option [ngValue]="undefined" disabled>searchByRegion</option>
<option >All</option>
<option >Asia</option>
<option >Europe</option>
<option >Africa</option>
<option >Australia</option>
</select>
this [ngValue]="undefined" is very important in 2nd line
May be I am somewhat late to this question
As @Thomas Watson answer does not work for angular 4 and upward so this best solution is :
<div class="col-md-4 mb-3">
<label for="gender">Gender</label>
<select class="custom-select" name="gender" id="gender" #gender ="ngModel" [(ngModel)]="employee.gender" required>
<option [ngValue]="null">Select Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<div class="text-danger" *ngIf="gender.invalid && gender.touched">Gender is required</div>
</div>
Then in the component :
ngOnInit(): void {
this.employee = new Employee();
this.employee.gender = null;
}
Note : This also works for required field validation
Angular 5 Solution and with Reactive forms!
<option value="null" disabled="true" [selected]="true">Placeholder text..</option>
:)
[ngValue]="myObject.myKey"
is what you want.
Below is my solution:
export default class AppComponent {
cityId: number = null
...
}
<select #chooceCity="ngModel" class="form-control" name="city [(ngModel)]="cityId" required>
<option *ngIf="chooceCity.untouched || chooceCity.invalid" value="null" disabled selected>Choose city</option>
<option *ngFor="let city of cities" [value]="city.id">{{city.name}}</option>
</select>
This code will hide placeholder as soon as correct answer will be selected.