我有原始申请。当我写编辑时,我需要设置默认输入并设置默认选择选项。对于输入来说,一切都很好。对于选择未设置默认值。我知道所选的属性,但它不起作用。 编辑组件:
export class EditStudComponent implements OnInit {
stud: Stud=new Stud();
grs: Array<Gr>;
sub: Subscription;
selected: Gr;
constructor(private route: ActivatedRoute, private router: Router, private
studService: StudService, private grService: GrService ) {
}
ngOnInit(): void {
this.sub = this.route.params.subscribe(params => {
const id = params['id'];
if (id) {
this.studService.getStud(id).subscribe((stud: any) => {
if (stud) {
this.stud = stud;
this.selected=this.stud.gr;
console.log(this.stud);
console.log(this.selected);
} else {
console.log(`Car with id '${id}' not found, returning to list`);
this.gotoList();
}
});
}
});
this.grService.getGrs()
.subscribe( data => {
this.grs = data;
});
}
editStud(): void {
this.studService.updateStud(this.stud)
.subscribe( data => {
alert("Edit successfully.");
});
};
}
edit.html
<select class="form-control" id="group" name="gr" size="1"
[(ngModel)]="stud.gr" >
<option *ngFor="let gr of grs" name="groups"
[ngValue]="gr" [selected]="gr==selected">
{{gr.name}}</option>
和屏幕:edit
答案 0 :(得分:1)
您应该比较selected.name == gr.name
,而不是比较两个对象。
<select class="form-control" id="group" name="gr" size="1" [(ngModel)]="stud.gr">
<option *ngFor="let gr of grs" name="groups" [ngValue]="gr"
[selected]="gr.name==selected.name">
{{gr.name}}</option>
答案 1 :(得分:0)
我散布了我的解决方案:
if (stud) {
this.stud.patronymic = stud.patronymic;
this.stud.course=stud.course;
this.stud.firstName=stud.surName;
this.stud.idStud=stud.idStud;
this.stud.surName=stud.surName;
this.selected=stud.gr;
console.log(this.stud);
console.log(this.selected);
edit.html
<option *ngFor="let gr of grs" name="grs"
[ngValue]="gr" [selected]="gr?.name==selected?.name">
{{gr.name}}</option>
但是解决方案并不简单。有人可以提出其他建议吗?