I have simple component that contains only form:
import {Component, FORM_DIRECTIVES, NgFor} from 'angular2/angular2';
@Component({
selector: 'test-component',
directives: [FORM_DIRECTIVES, NgFor],
template: `
<form class="form-inline" (ng-submit)="onSubmit()" #form="form">
<div class="form-group">
<select class="form-control"
[(ng-model)]="model.server"
ng-control="server"
#server="form"
required>
<option selected hidden>placeholder</option>
<option *ng-for="#server of servers"
[value]="server">{{ server | uppercase }}
</option>
</select>
</div>
<div class="form-group">
<input class="btn btn-primary" type="submit" value="Load"
[disabled]="!form.form.valid">
</div>
</form>
`
})
export class TestComponent {
public model: Model = new Model();
public servers: string[] = ['a', 'b', 'c'];
onSubmit(): void {
// Complicated logic.
// Reset form.
this.model.reset();
}
}
class Model {
constructor(
public server: string = ''
) { }
reset(): void {
this.server = '';
}
}
I want to create "placeholder" for my select, however ng-model overrides selected property which cause no selected option at all. Any sugestions? I am using angular 2.0.0-alpha.48.
Answer: Use the disabled and selected Attribute There is no attribute like input's placeholder for select box dropdown. However, you can create similar effect by using the HTML disabled and selected attribute on a <option> element that has empty value.
There is no placeholder attribute in 'select' tag but it can make the placeholder for a 'select' box. There are many ways to create the placeholder for a 'select' box.
Use Angular placeholders for your components or pages to indicate something may still be loading.
Angular 5 Solution and with Reactive forms!
<option value="null" disabled="true" [selected]="true">Placeholder text..</option>
:)
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" [(ngModel)]="mySelect">
<option value="-1">Placeholder text..</option>
<!-- forloop of options heres -->
</select>
Then in your component. this.mySelect = -1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With