0

I'm getting roles from rest-api in my component like:

this.userService.getRoles().subscribe(data => this.roles = data);

Then I'm trying to use it in my template as below:

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

But it's not working, output for {{roles | json}}, so everything is fine with them, the problem is select doesn't work.

[{"id":1, "name":"user"}, {"id":2, "name":"admin"}]
6
  • any errors in the console Commented Aug 8, 2018 at 10:42
  • @SachilaRanawaka ERROR TypeError: "_co.user is undefined" Commented Aug 8, 2018 at 10:44
  • define the user object on your component user = { role: 'user'} Commented Aug 8, 2018 at 10:46
  • @SachilaRanawaka user is defined as well, output for {{user | json}} is { "id": 1, "login": "admin", "password": "admin", "email": "[email protected]", "firstName": "Admin", "lastName": "Johnson", "birthday": "1995-06-06", "role": { "id": 2, "name": "admin" } } Commented Aug 8, 2018 at 10:48
  • @SachilaRanawaka it doesn't work even without ngModel directive, I've tried everything. Is anything need to be imported for using angular select? Commented Aug 8, 2018 at 10:49

1 Answer 1

2

Use [compareWith]. Stackblitz

@Component({
  selector: 'hello',
  template: `
    <select [(ngModel)]="selected" [compareWith]="compare">
      <option *ngFor="let role of roles" [ngValue]="role">{{ role.desc }}</option>
    </select><br>
    <p>Selected role : {{ selected | json }}</p>
  `,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {

  roles = [
    {id: 1, desc: 'Admin' },
    {id: 2, desc: 'User' },
  ];

  selected: any;

  compare(obj1, obj2) {
    return obj1 && obj2 && obj1.id === obj2.id;
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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.