Reputation: 11
I have crud application. When I write edit, i need set default input and set deault select option. For input all is good. For select is not set default value.I know about property selected, but it is not work. edit-component:
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>
and screen:edit
Upvotes: 1
Views: 48
Reputation: 11
I spread my solution:
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>
But the solution is not trivial. Can anyone suggest anything else?
Upvotes: 0
Reputation: 29705
You should compare selected.name == gr.name
, instead of comparing two objects.
<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>
Upvotes: 1