简体   繁体   中英

Angular7 - Autofill ng-select

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-选择

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM