Angular5 ngselect with object not select



我对Angular很陌生,我正在寻找一种解决这个问题的好方法,但我读过的帖子并不相关。

我有一个需要存储对象的第一个下拉列表,然后在选择后,还有一个需要填充的第二个下拉列表。这是在"用户首选项页面"上,因此需要保存所选的值。到目前为止,这是有效的(控制器将选定的值保存在服务中,当返回到首选项页面时,我将selectedValues放回服务中的任何值——我猜这是正确的方法(。

问题是,当离开该页面并返回时,第一个下拉列表不会选择用户之前选择的内容(存储对象"LsafIdp"(,而第二个下拉列表会选择(存储简单字符串(。我应该如何处理此问题,以便第一个下拉列表显示所选对象?

注意:我正在运行Angular 5

HTML文件

<div class="form-group">
<label for="idp">IDP</label>
<select class="form-control" id="idp" required [(ngModel)]="selectedIdp" name="idp" (change)="onIdpSelection()">
<option *ngFor="let idp of idps" [ngValue]="idp">{{idp.idpName}}</option>
</select>
</div>
<div class="form-group">
<label for="study">Study</label>
<select class="form-control" id="study" required [(ngModel)]="selectedStudy" name="study" (change)="onStudySelection()">
<option *ngFor="let study of selectedIdp.studyList" [ngValue]="study">{{study}}</option>
</select>
</div>
Selected:
<p>IDP as json: {{selectedIdp | json}}</p> <!-- this works, shows correctly the object saved in the service -->
</form>

TS文件:

@Component({
selector: 'app-context',
templateUrl: './context.component.html',
styleUrls: ['./context.component.scss'],
//encapsulation: ViewEncapsulation.Emulated
})
export class ContextComponent implements OnInit {
selectedIdp: LsafIdp; // model for the first <select>
selectedStudy: string; // model for the 2nd <select>
idps: LsafIdp[];
constructor(private lsafService: LsafService) {
this.selectedIdp = new LsafIdp();
}
ngOnInit() {
// on init load the values from the service
if(this.lsafService.idpSelected!=null)
this.selectedIdp = this.lsafService.idpSelected;
if(this.lsafService.studySelected!=null)
this.selectedStudy = this.lsafService.studySelected;
this.lsafService.getLsafInfo().subscribe(
response => {
let lsafInfo: LsafInfo = response;
this.idps = lsafInfo.idpList;
}
);
}
onIdpSelection() {
console.log("IDP selected: " + this.selectedIdp.idpName);
this.lsafService.idpSelected = this.selectedIdp;
}
onStudySelection() {
console.log("Study selected: " + this.selectedStudy);
this.lsafService.studySelected = this.selectedStudy;
}

}

我尝试了很多事情,比如:(对这一次有很多希望(

<option *ngFor="let idp of idps" [ngValue]="idp" [selected]="idp.idpName === selectedIdp.idpName">{{idp.idpName}}</option>

但我所有的尝试都失败了

谢谢!

好的,经过大量研究,我终于找到了

正确的方法是在<select>上使用[compareWith],并在控制器中定义该方法。

<select class="form-control" id="idp" required [(ngModel)]="selectedIdp" name="idp" (change)="onIdpSelection()" [compareWith]="compareIdpByName" >
<option *ngFor="let idp of idps" [ngValue]="idp">{{idp.idpName}}</option>
</select>
compareIdpByName(item1: LsafIdp, item2: LsafIdp){
return item1.idpName === item2.idpName;
}

最新更新