Angular2 [选择]无法设置默认值?
我试图设置默认值我的选择,所以我尝试Angular2 [选择]无法设置默认值?
[selected]= "selected_choice == 'one'"
像这样
但这并没有工作。
人们说[选择]不再工作,所以我也试过[attr.selected],但没有工作以及..
这是我的一个选择标签
<select (change)="passValue3()" formControlName="school" class="form-control" required [(ngModel)]="selected_student" class="selectionbox">
<option *ngIf="selected_student == undefined">학년 선택</option>
<option *ngFor="let gradetype of gradeTypes" [ngValue]="gradetype" [attr.selected] = "gradetype.gradeType === 'Middle'">{{gradetype.gradeName}}</option>
</select>
整个代码我如何设置选择的默认选项?
它不起作用,因为您的选择应该具有[(ngModel)]
属性。
您只需将此值设置为您想要选择的值,并且您应该很好。
我已经有ngModel – Lea
然后给它你想要选择的值。 – trichetriche
[selected] =“selected_student ==='Middle'”不起作用 – Lea
你需要做这样的事情:
在标记:
<select placeholder="Sample select" [(ngModel)]="selectedItem">
<option [value]="'all'">View All</option>
<option [value]="'item-1'">Item-1</option>
<option [value]="'item-2'">Item-2</option>
</select>
在组件
selectedItem='all'
为我工作。谢谢。 – himanshupareek66
这里是我的解决方案:
示例是关于时区。从后端我的下一个对象项目:
activeItem = { "timezone": { "timeZoneHolder": "Europe", "region": "Europe/Paris (CEST)", "UTC": "UTC+1" }}
而且从我的模型相同的项目看起来有点不同,因为源变化:
{ "timeZoneHolder": "France", "region": "Europe/Paris", "UTC": "UTC +01:00" }
正如你看到的有点不同。
因此,这里是我的模型:
timeZones = [{ "timeZoneHolder": "France", "region": "Europe/Paris", "UTC": "UTC +01:00" }, { "timeZoneHolder": "French Polynesia", "region": "Pacific/Gambier", "UTC": "UTC -09:00" }]
这里是加价的选择,就像一个魅力:
<select id="timezone" name="timezone" [(ngModel)]="activeItem.timezone">
<option [ngValue]="activeItem.timezone" [selected]="true" disabled hidden>{{activeItem.timezone.region}}</option>
<option *ngFor="let timeZone of timeZones"
[ngValue]="{timeZoneHolder: timeZone.countryName, region: timeZone.timeZone, UTC: timeZone.UTC}">
{{timeZone.timeZone}}
</option>
享受:)
你比较选项通过compareWith
属性来选择,如果你使用角度4,可能会不会在角2上工作。
HTML文件:
<select [compareWith]="byAnimal" [(ngModel)]="selectedAnimal">
<option *ngFor="let animal of animals" [ngValue]="animal">
{{animal.type}}
</option>
</select>
TS文件
byAnimal(item1,item2){
return item1.type == item2.type;
}
一个最好的soltion从这个link
这是基于绑定到'option'什么,见https://*.com/questions/44044746/selected-of-select-doesnt-work-as-excepted-in-angular2,也htt ps://*.com/questions/44042797/angular-2-set-selected-on-a-select-option-dropdown/44043801#44043801欲了解更多信息。 – Pengyy