1

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.

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

This should work like you did. Notice that could put your select within a form element:

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

See this plunkr: https://plnkr.co/edit/J1aVclVcjJPqm1Qx9j0j?p=preview.

1 Comment

Which version of Angular2 do you use?
1

It's hard to find answers for particular angular versions... so while searching for this issue while using a more recent version (angular 4.4.5), I've stumbled upon this thread. However none of the answers work for me so here is my solution for newer versions, in case someone else might stumble upon this thread too :-)

<select class="form-control" [(ngModel)]="size" name="sizeValue" #sizeValue="ngModel">
  <option *ngFor="let size of sizes" [value]="size">{{size}}</option>
</select>

In particular this part: name="sizeValue" #sizeValue="ngModel" on the select element.

1 Comment

Thanks. I agree about the angular versions when trying to find something for angular 4 or higher. BTW your comment was my solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.