0

I have the following code

<select name="role" [(ngModel)]="user.role">
    <option *ngFor="let r of roles" [ngValue]="r">{{r.name}}</option>
</select>

where roles is an Object:

[{"id":1, "name":"user"}, {"id": 2, "name":"admin"}]

and user.role is for example:

{"id":1, "name":"user"}

I want initial value to be the user.role, I've tried a lot of things like ngInit, but it didn't get the job done.

5
  • the problem is that [ngValue] is an object. So use user.role=roles[0]; (NOTE:If you use [ngValue]="r.id", you can use user.role=roles[0].id Commented Aug 9, 2018 at 8:44
  • @Eliseo, why should I? lol Commented Aug 9, 2018 at 8:47
  • it's strange that user.role was an object. I think you want that user.role was a number (1 or 2), not {id:1,name:admin} Commented Aug 9, 2018 at 8:49
  • @Eliseo I'm using Spring data jpa on my backend to get full user role, why should it be the number? It's my own object of Role class actually. Commented Aug 9, 2018 at 8:53
  • In only was trying to help you. of course you can use an object or whatever you want Commented Aug 9, 2018 at 9:45

1 Answer 1

2

You can try with this solution.

I have create a demo on Stackblitz

use [compareWith]="compareObjects" for use object in select

component.html

<select name="role" [compareWith]="compareObjects" [(ngModel)]="user.role">
    <option *ngFor="let r of roles" [ngValue]="r">{{r.name}}</option>
</select>

component.ts

  user = {
    role: { "id": 1, "name": "user" }
  }
  roles = [
    { "id": 1, "name": "user" }, 
    { "id": 2, "name": "admin" }
  ]

  compareObjects(o1: any, o2: any): boolean {
    return o1.id === o2.id && o1.name === o2.name;
  }
Sign up to request clarification or add additional context in comments.

1 Comment

too complex, it's not necesary

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.