Angular TypeScript下拉列表未选择默认值

时间:2019-03-28 05:06:00

标签: html angular select

尝试使用Angular打字稿设置下拉菜单的默认选定值时遇到问题。
这是我的html代码:

 <div class="row">
            <div class="form-group col-md-2">
                <strong><label class="form-control-label" 
                jhiTranslate="staff.department" 
                for="field_department">Department</label></strong>
            </div>
            <div class="form-group col-md-4">
                <select class="form-control" id="field_department" 
                name="department" [(ngModel)]="staff.department">
                    <option [ngValue]="null" selected disabled>
                     Please select an Option</option>
                    <option [ngValue]="departmentOption.id === staff.department?.id ? 
                    staff.department : departmentOption" 
                 *ngFor="let departmentOption of departments | orderBy: 'departmentName'">
                   {{departmentOption.departmentName}}</option>
                </select>
            </div>
        </div>

默认情况下,启动页面时,"Please select an Option"的下拉选项应该显示在下拉菜单中,但就我而言,它是空的。知道为什么会这样吗?

谢谢!

3 个答案:

答案 0 :(得分:0)

您可以尝试初始设置staff.department=null

在ts

ngOnInit() {
 this.staff.department=null
}

以html

<select class="form-control" id="field_department" name="department" [(ngModel)]="staff.department">
     <option [ngValue]=null disabled>Please select an Option</option>
        //rest code
</select>

答案 1 :(得分:0)

尝试将"anyvariable that is not defined in typescript"作为选项的默认值

<select class="form-control" id="field_department" name="department"
 [(ngModel)]="staff.department">
             <option [ngValue]="anythingNotDefinedYet" selected disabled>
             Please select an Option</option>
             <option [ngValue]="departmentOption.id === 
             staff.department?.id ? staff.department : departmentOption" 
             *ngFor="let departmentOption of departments | orderBy: 'departmentName'">
             {{departmentOption.departmentName}}</option>
  </select>

Stackblitz Demo showing the case

答案 2 :(得分:0)

尝试<option [ngValue]="undefined" selected disabled>Please select an Option</option>