typescript Angular4 - 如何动态设置选择选项值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46306873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:54:01  来源:igfitidea点击:

Angular4 - How to set select option value dynamically

javascripthtmlangulartypescript

提问by Vipul Sharma

I have a select list with the code -

我有一个带有代码的选择列表 -

<select (change)='onGroupChange($event)'>
    <option *ngFor="let group of groups" value={{group.group_name}}>
        {{group.group_name}}
    </option>
</select>

Now I have a group name value saved as a different variable and I want to set that as the select list value if it matches any.

现在我有一个组名值保存为不同的变量,如果它匹配任何值,我想将其设置为选择列表值。

采纳答案by Michael

<select (change)='onGroupChange($event)'>
    <option *ngFor="let group of groups" value={{group.group_name}} [selected]="group.group_name==myVariable">
        {{group.group_name}}
    </option>
</select>

回答by Hui Shi

<select [(ngModel)]="selectedGroup" (ngModelChange)="onGroupChange($event)">
    <option *ngFor="let group of groups" [value]="group.group_name">
    {{group.group_name}}
    </option>
</select>