如何提供选定的选项标签 - Angular 2

时间:2017-02-09 05:30:25

标签: angular

我有一个简单的select标签,用于从数据库中提取数据。

<select *ngIf="projects.length" [(ngModel)]="selectedProject">
<option *ngFor="let projectTypeModel of projects" [ngValue]="projectTypeModel">{{projectTypeModel.ProjectName}}</option>
</select>

我想显示文本“选择项目类型”以选择默认值。 我添加的代码是:

<select *ngIf="projects.length" [(ngModel)]="selectedProject">
 <option [selected]="true">Select Project Type</option>
 <option *ngFor="let projectTypeModel of projects" [ngValue]="projectTypeModel">{{projectTypeModel.ProjectName}}</option>
 </select>

但这不起作用。有什么指针吗?

1 个答案:

答案 0 :(得分:0)

试试这个

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <select *ngIf="projects.length" [(ngModel)]="selectedProject">
     <option [selected]="true" value="" disabled>Select Project Type</option>
     <option *ngFor="let opt of projects" [value]="opt.value">{{opt.ProjectName}}</option>
    </select>
  `
})
export class AppComponent {
  selectedProject: string = ''; // string or number

  projects = [
    { ProjectName: "option 1", value: 'op1' },
    { ProjectName: "option 2", value: 'op2' },
    { ProjectName: "option 3", value: 'op3' },
  ];
}

在线演示:https://plnkr.co/edit/rNHjQs?p=preview