20 fps
20 fps

Reputation: 342

Angular 6 select: set initial value

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.

Upvotes: 0

Views: 2659

Answers (1)

Krishna Rathore
Krishna Rathore

Reputation: 9687

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;
  }

Upvotes: 2

Related Questions