0

I have a view with an id in URL. When loading this view I call service and take all user data, looks similar to.

{
    "code": 0,
    "message": "",
    "body": {
        "id": 1,
        "name": "test",
        "profile": [
            {
                "id": 2,
                "description": "admin"
            },
            {
                "id": 1,
                "description": "user"
            }
        ]
    }
}

Suppose that user doesn't have profiles, so select component only has all array data. In other case suppose that user has an admin profile, so select component has all array but admin is the default selected.

In HTML i have

 <ng-select [multiple]="true"  name="perfiles" placeholder="{{ 'profile-placeholder' | translate }}"
        [(ngModel)]="perfiles">
        <ng-option *ngFor="let perfil of perfiles"  bindLabel="perfil.descripcion" [value]="perfil.id" >{{perfil.descripcion}}</ng-option>
      </ng-select>

And the result is.

ng-select

The problem is that component doesn't show any data. Apparently works, a user has two profiles, but I don´t know how show description. Any help?

El Hombre Sin Nombre
  • 2,906
  • 18
  • 49
  • 92

2 Answers2

0

I think you made a typo in your html:

    <ng-option *ngFor="let perfil of perfiles"  bindLabel="perfil.descripcion" [value]="perfil.id" >{{perfil.descripcion}}</ng-option>

it should be:

    <ng-option *ngFor="let perfil of perfiles"  bindLabel="perfil.description" [value]="perfil.id" >{{perfil.description}}</ng-option>

I changed {{perfil.descripcion}} to {{perfil.description}} and bindLabel="perfil.descripcion" to bindLabel="perfil.description" according to your JSON, this should work now.

Korfoo
  • 571
  • 2
  • 12
0

I found the solution. In first time I need to get all elements in a array with a web service. Then we need to save all elements in a variable.

//Declare a variable 
private allElements: any= [];
//Save web response data in a variable
this.allElements= response["body"];

We need to do same to get user elements in array. We need new web service for search user elements.

//Declare a variable 
private userElements: any= [];
//Save web response data in a variable. This response only has user data.
this.userElements= response["body"];

Finally in HTML we need.

 <ng-select [items]="allElements"  [multiple]="true" name="userElements" bindLabel="description"
 [(ngModel)]="userElements">
 </ng-select>

This create a loop over allElements to fill select component and show userElements as default.

El Hombre Sin Nombre
  • 2,906
  • 18
  • 49
  • 92