如何使用Angular 2设置HTML选择值 [英] How to set HTML select value with Angular 2

查看:62
本文介绍了如何使用Angular 2设置HTML选择值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从Angular2组件的HTML下拉列表中设置选定的值.我看不到它是否应该正常工作,或者我需要更复杂的东西

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>

组件

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

    ...

    constructor() {
    }
}

从此代码中,我希望一开始会选择具有值 4 的ítem,但这不会发生.

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

推荐答案

为我工作

@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'}]

}

提示: * ngFor 在beta.17中的语法略有不同( let 代替#)

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

柱塞示例

这篇关于如何使用Angular 2设置HTML选择值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆