0

我对 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>

但我所有的尝试都失败了

谢谢!

4

1 回答 1

0

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

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

    <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;
}
于 2018-07-21T13:30:20.877 回答