如何将第一个选项设置为选中位置,其中选项从循环中的选择框anular 4中生成 [英] How to set first option as selected where options build from loop in select box anular 4

查看:36
本文介绍了如何将第一个选项设置为选中位置,其中选项从循环中的选择框anular 4中生成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从事过angular 4项目,在这个项目中,我需要将第一个选项设置为选中状态,其中所有选项都是通过循环动态创建的. html代码:

I have worked on angular 4 project, In this project, I have a requirement to set the first option as selected where all options are created dynamically by loop. html code:

<select [(ngModel)]="selectedServiceType" [ngModelOptions]="{standalone: true}" (ngModelChange)="getServiceType($event)">
    <ng-container *ngFor="let service of services">
        <option [ngValue]="service">{{service.name}}</option>
    </ng-container>
</select>

如果有人知道,请告诉我.预先感谢!

If anyone know about let me know. Thanks in advance!

推荐答案

尝试这样:

<select class="form-control" (change)="onChange($event)">
    <option *ngFor="let service of services; let itemIndex = index" [selected]="itemIndex == 0" [ngValue]="service.value">{{service.name}}</option>
</select>

component.ts

export class HomeComponent implements OnInit {

    private selectedServiceType: any;
    private services: Array<any> = [];

    constructor() {
        this.services = [{
            name: "Harish",
            value: 5000
        }, {
            name: "Chandru",
            value: 5001
        }]
    }
    onChange(e) {
        this.selectedServiceType = e.target.value;
    }
}

这篇关于如何将第一个选项设置为选中位置,其中选项从循环中的选择框anular 4中生成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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