angular - 如何将第一个选项设置为选定的选项,其中选项是从选择框 anular 4 中的循环构建的

标签 angular angular4-forms

我曾参与 Angular 4 项目,在这个项目中,我需要将第一个选项设置为选定的,其中所有选项都是通过循环动态创建的。 html代码:

<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>

如果有人知道请告诉我。提前致谢!

最佳答案

尝试这样:

<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>

组件.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;
    }
}

关于angular - 如何将第一个选项设置为选定的选项,其中选项是从选择框 anular 4 中的循环构建的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46616879/

相关文章:

angular - 防止angular7中的默认上下文菜单

listview - NativeScript Angular 2 Firebase 列表不起作用

javascript - 尽管 URL 正确,Angular Router 仍不加载我的组件

node.js - 类型错误 : Cannot read property '_id' of undefined in Angular4

angular - 选择框默认值未显示 [(ngModel)] Angular 2

angular - formbuilder 的 patchvalue 或 setvalue 不会将字段标记为脏或已触摸

javascript - 如何在 Angular 中使用外部链接指令?

javascript - 如何在调用同一事件的同时保持一个事件

Angular FormArray插入

angular - 使用 Angular 4 在单个组件中加载动态模板