I have simple component that contains only form:
import {Component, FORM_DIRECTIVES, NgFor} from \'angular2/angular2\';
@Component({
selector: \'test-com
@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 of selectedState
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 2
stateList.ts
export const STATELIST : US_States[] =[
{
"name":"State",
"code":""
},
{
"name": "Alabama",
"code": "AL"
},
{
"name": "Alaska",
"code": "AK"
}, ...
];
Note: I chose the first entry as the placeholder, as shown below in
form.component.ts
stateList:US_States[] = STATELIST;
public selectedState: US_States = Object.assign({}, this.stateList[0]);
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 operator this.stateList[0] = state.code;