Home Set default value for dropdown list FormGroup
Reply: 2

Set default value for dropdown list FormGroup

Phạm Quốc Bảo
1#
Phạm Quốc Bảo Published in 2017-11-14 15:23:11Z

I have 2 response data from my API like as: List all roles:

{
  "content": [{
      "id": 1,
      "roleName": "admin",
    },
    {
      "id": 2,
      "roleName": "user",

    },
    {
      "id": 3,
      "roleName": "other",

    }
  ],
  "last": true,
  "totalElements": 3,
  "totalPages": 1,
  "size": 20,
  "number": 0,
  "first": true,
  "sort": null,
  "numberOfElements": 3
}

and user info:

{
  "id": 1,
  "userName": "admin"
  userRole[
    "id": 1,
    "roleName": "admin",
  ]
}

in HTML, I want to show the list role:

<div class="form-group">
  <label>Roles</label>
  <select formControlName="roles" class="form-control" id="roles">
    <option>{{user.userRole.roleName}}</option>
    <option *ngFor="let ls of roles">{{ls.roleName}}</option>
  </select>
</div>

but, the UI shows : [admin],[admin],[user],[other]

I try to remove the duplicate role by using *ngIf:

<div class="form-group">
  <label>Roles</label>
  <select formControlName="roles" class="form-control" id="roles">
    <option>{{user.userRole.roleName}}</option>
    <option *ngFor="let ls of roles">
      <div *ngIf="user.userRole.roleName!=ls.roleName">{{ls.roleName}}</div>
    </option>
  </select>
</div>

but the UI shows:[admin],[blank],[user],[other]

Please advice me to show the list role correctly.

classicalConditioning
2#
classicalConditioning Reply to 2017-11-16 14:53:13Z
<div class="form-group">
  <label>Roles</label>
  <select formControlName="roles" class="form-control" id="roles">
    <option *ngFor="let ls of roles" [selected]="ls.id === user.userRole.id">
      {{ls.roleName}}
    </option>
  </select>
</div>
Phạm Quốc Bảo
3#
Phạm Quốc Bảo Reply to 2017-11-16 14:22:59Z

I found the solution to user [attr.selected]:

 <select formControlName="roles" class="form-control" id="roles"  >
                        <option *ngFor="let rl of roles;" 
                        [attr.value]='rl.id' 
                        [attr.selected]="rl.id == desc ? true : null">
                           {{rl.roleName}}
                          </option>
                    </select>
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.320462 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO