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.
I could not get any of the above answers working for me on Chrome 60.0.3112.113. Mainly, using
value="null"
, orvalue=""
on the placeholder option left the option blank in the select box. In my attempts, the value needed to me the text of the placeholder for it to show up.component:
html:
Plunker here: https://plnkr.co/edit/VPj86UTw1X2NK5LLrb8W
The action button is disabled until the selected value is not equal to the default placeholder text value.
*I was getting errors using ngModel (plunker only), so I used a
(change)
function on the select to update the selected value.Then in your component.
this.mySelect = -1;
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 :
Then in the component :
Note : This also works for required field validation
Angular 5 Solution and with Reactive forms!
:)
I got this to work by doing the following:
then using css ng-pristine for styling
Below is my solution:
This code will hide placeholder as soon as correct answer will be selected.