我最近一直在使用Angular 7,在尝试显示下拉列表并在此列表中显示默认值时发现一些奇怪的事情。这分别是两个单独的列表:
sample.component.html
<select [(ngModel)]="organization" id="organization" required>
<option *ngFor="let organization of organizations" [value]="organization.id" [ngValue]="organization.name">{{organization.name}}</option>
</select>
<br>
我发现上面的代码在我的浏览器中显示以下内容:
请注意上面的默认值设置方式,但在下一个下拉列表中未设置默认值:
sample.component.html
<select [(ngModel)]="seniorExperience" id="seniorExperience" required>
<option *ngFor="let seniorExperience of seniorExperiences" [value]="seniorExperience.seniorExperienceId" [ngValue]="seniorExperience.seniorExperienceName">{{seniorExperience.seniorExperienceName}}</option>
</select>
浏览器显示以下内容:
为什么在使用相同语法时第二个下拉列表没有使用默认填充?通过搜索和阅读文档,我认为[ngValue]设置了下拉菜单的默认值,这似乎适用于第一个下拉菜单。有没有更好的方法来设置默认选择?
答案 0 :(得分:2)
按照Angular 7实现:
<select *ngIf="ownerLevels" [value]="selectedOwnerLevel" (change)="onChangeOwnerLevel($event.target.value)" formControlName="ownerLevel" id="ddOwnerLevel">
<option [value]="0" disabled>Select Owner Level</option>
<option *ngFor="let ownerLevel of ownerLevels" [value]="ownerLevel.id">{{ownerLevel.name}}</option>
</select>
ownerLevels = [
{ id: 1, name: 'Company' },
{ id: 2, name: 'Department' },
{ id: 3, name: 'Personal Area' }
];
selectedOwnerLevel: number = 0;
onChangeOwnerLevel(ownerLevelId: number) {
this.selectedOwnerLevel = ownerLevelId;
}