我在Angular ngFor循环中有一个选择HTML元素:
<select formControlName="type" required>
<option *ngFor="let type of typeList" [ngValue]="type.value">{{ type.caption }}</option>
</select>
在Internet Explorer中,列表中的第一个项目在模板加载时被选中,但它的值未在表单控件中设置,因此会导致“必需”验证错误,直到在列表中选择了另一个值。我想要一个具有空值的“请选择”选项以防止这种情况发生。
这适用于使用或不使用TypeScript的Angular 2+
像这样添加一个选项:
<option [ngValue]="null">Please select</option>
所以你的控件看起来像:
<select formControlName="type" required>
<option [ngValue]="null">Please select</option>
<option *ngFor="let type of typeList" [ngValue]="type.value">{{ type.caption }}</option>
</select>
这可以作为Angular检查value属性,因为方括号。该值变为true null,不像我们使用value =“”(这只是一个空字符串并且不匹配null)。
component.ts
public selectedValue = 'None';
component.html:
<div ">
<label>Highlight</label>
<select [(ngModel)]="selectedTrunk" (change)="onChangeTrunk($event)">
<option value='None'>None</option>
<option *ngFor="let trunklist of DRLNameTrunkList" [selected]="trunk" [value]="trunklist.SIPTRUNKNAME">{{trunklist.SIPTRUNKNAME}}</option>
</select>
</div>
这是我的代码,请根据您的要求进行修改