在下拉列表中设置所选项目

时间:2018-12-27 14:55:01

标签: angular html-select

一个简单的问题, 如何在下拉列表中设置所选项目!

简单的HTML https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_option_selected

但是当Angular进来的时候,每件事都变得混乱了!!

这是我的问题的现场演示

https://stackblitz.com/edit/angular-jrvpus?embed=1&file=src/app/app.component.html

2 个答案:

答案 0 :(得分:1)

<select class="form-control" [(ngModel)]="ItemId" (change)="DoSomeThingMethods()"
                    name="itemsfromServer" required>
                <option *ngFor="let item of itemsfromServer" value="{{ item.ItemId }}" [selected]="item.ItemId == 0 ">{{ item.type }} {{ item.ItemId }}</option>
            </select>

现在在组件中设置[(ngModel)]值。

如果将ItemId设置为0{ItemId : 0 ,selected : true ,type:"Type default"}将在下拉列表中选择。

答案 1 :(得分:1)

您可以通过ngModel进行设置。

考虑您的模板HTML;

<select [(ngModel)]="id" (change)="change()" name="item" required>
    <option *ngFor="let item of items" value="{{ item.id }}">
        {{ item.type }}
    </option>
</select>

在你的component.ts中;

this.id = 5; //or whatever

现在,如果收藏的物品是这样的

[
    {type:"t1", id:"1"},
    {type:"t2", id:"2"},
    {type:"t3", id:"3"},
    {type:"t4", id:"4"},
    {type:"t5", id:"5"},
    {type:"t6", id:"6"},
    {type:"t7", id:"7"},
]

现在应该默认选择type : t5

相关问题