StackOverflower StackOverflower - 7 months ago 265
Javascript Question

How to set HTML select value with Angular 2

I want to set selected value from an HTML dropdown from a Angular2 component. I'm failing to see if this should be working or I need something more complex

HTML

<select class="form-control" id="role" [ngModel]="SelectedRole">
<option *ngFor="#option of Roles" [value]="option.Value">{{option.Text}}</option>
</select>


COMPONENT

export class MyComponent extends Secured {
public SelectedRole: String = "4";

...

constructor() {
}
}


From this code, I'd expect ítem with value
4
to be selected at the begining and that's not happening.

Answer

Works for me

@Component({
    selector: 'my-app',
    template: `
    <h1>Hello</h1>
<select class="form-control" id="role" [ngModel]="selectedRole">
  <option *ngFor="let option of roles" [value]="option.value">{{option.text}}</option>
</select>
    `,
})
export class AppComponent {
  public selectedRole: String = "4";
  roles = [{value: '1', text: '1'}, {value: '2', text: '2'}, {value: '3', text: '3'}, {value: '4', text: '4'}]

}

Hint: *ngFor has a slightliy different syntax in beta.17 (let instead of #)

Plunker example