我在Angular 4中遇到了选择标记的问题。这是我的代码。
update.component.html:
<div class="animated fadeIn" *ngIf="organization">
...
<div class="form-group animated fadeIn" *ngIf="organizationTypes">
<label for="searchOrgType">Тип організації</label>
<select [(ngModel)]="organization.organizationType" class="form-control" id="searchOrgType" name="searchOrgType" #searchOrgType="ngModel">
<option [ngValue]="null">Choose type</option>
<option *ngFor="let type of organizationTypes" [ngValue]="type">{{type.name}}</option>
</select>
</div>
update.component.ts:
ngOnInit() {
this.route.params.subscribe(params => {
this.organizationService
.getItem(+params['id'])
.subscribe(
organization => {
this.organization = organization;
this.titleService.setTitle('Update - ' + this.organization.name);
})
});
this.getOrganizationTypes();
this.getTaxTypes();
}
...
private getOrganizationTypes(): void {
this.organizationTypeService.getList()
.subscribe(types => this.organizationTypes = types);
}
获取组织和类型列表可以正常工作。所以我在选择列表和组织信息中看到了我需要的所有选项。
但是选择值仅适用于空值。所以,如果 organization.organizationType == null ,我会看到&#34;提示&#34; 按预期选择类型值。但是如果组织类型不为null,我会看到空的选择值。我尝试添加[selected] with object和id&#39的比较,但没有效果。
是的,有人可以帮帮我吗?无法理解我做错了什么。答案 0 :(得分:0)
尝试使用compareWith
指令
https://angular.io/api/forms/SelectControlValueAccessor#syntax
(以下示例假设您的对象具有唯一的id
属性)
<select [(ngModel)]="organization.organizationType" class="form-control" id="searchOrgType" name="searchOrgType" #searchOrgType="ngModel" [compareWith]="compareFn">
<option [ngValue]="null">Choose type</option>
<option *ngFor="let type of organizationTypes" [ngValue]="type">{{type.name}}</option>
</select>
compareFn(o1: OrganizationType, o2: OrganizationType): boolean {
return o1 && o2 ? o1.id === o2.id : o1 === o2;
}