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.
Below is my solution while using Reactive forms
is what you want.
This worked for me in Angular 5 using reactive forms, for a dropdown that's a
FormControl
. The key is:[null]
in the TypeScript[ngValue]="null"
on the placeholder option(or you could use
0
or a negative number instead ofnull
).ts
html
From https://netbasal.com/angular-quick-tip-how-to-show-a-placeholder-in-select-control-bab688f98b98
Works for me.
this work for me
my answer is based on this answer and this answer
@Thomas's answer above got me almost there, but
[selected]
is ignored when using[(ngModel)]
. @Baconbeastnz's answer can work, but it fails to address form validation.Here is an answer that I got from piecing together answers from around the internet.
form.html
Note: I purposely chose
selectedState.code
instead ofselectedState
for form validation purposes.Note2: I chose to disable the placeholder "State" option. Note2: This may be a hack, but
minlength
is used for form validation purposes, and checks if the code is a minimum length of 2stateList.ts
Note: I chose the first entry as the placeholder, as shown below in
form.component.ts
Note: At first, I simply assigned selectedState = this.stateList[0], but what that does is assign by reference, not value. I needed
Object.assign
to make a copy of the first entry of the stateList value. Otherwise, any selection of other values in the dropdown will perform the operatorthis.stateList[0] = state.code;