how to properly bind loaded data to @ng-select, angular5

Juan I. Morales Pestana picture Juan I. Morales Pestana · Mar 26, 2018 · Viewed 13.4k times · Source

Working with angular 5 and @ng-select I found some issues binding to previously selected data(in edit forms an such as)

Ngselect definition

 <ng-select
     [items]="contenedores$ | async"
     bindLabel="numero"
     bindValue="id"
     [(ngModel)]="embarqueContenedor.contenedor"> 
 </ng-select>

From the api I serialize the entity this way:

Received from server (json)(this is from the model)

{
    "id": 1,
    "numero": "dsvsd",
    "dimension": 234,
    "tipoContenedor": "324",
    "contenedorEmbarques": [],
    "text": "dsvsd",
    "value": 1,
    "name": "dsvsd",
    "createdAt": "2018-03-26T12:44:48-04:00",
    "updatedAt": "2018-03-26T12:44:48-04:00"
}

also I fill the ngselect with the items. I received from the server an array with objects like above(actually are the same entity so they are serialized the same way)

Following this doc and this one I tried to use both so I add some extra serialized fields(ummaped) and got the above json (text=name=numero,id=value). The problem is that is not working at all, still getting this error from ng-select.js each time I had a selected choice:

Binding object({"id":2,"numero":"dfdhdf","dimension":324234,"tipoContenedor":"324324","contenedorEmbarques":[],"text":"dfdhdf","name":"dfdhdf","value":2,"createdAt":"2018-03-26T12:44:48-04:00","updatedAt":"2018-03-26T12:44:48-04:00"}) with bindValue is not allowed.

The objects have the same and required attributes but still not work

Any help?

Answer

chrispy picture chrispy · Mar 26, 2018

This line is how they are validating that your backing value is valid:

    const validateBinding = (item: any): boolean => {
        if (isObject(item) && this.bindValue) {
            this._console.warn(`Binding object(${JSON.stringify(item)}) with bindValue is not allowed.`);
            return false;
        }
        return true;
    };

That's where your error is coming from. I would guess that this line:

[(ngModel)]="embarqueContenedor.contenedor"

is messing it up, as the ngModel is pointing at an object instead of an id per bindValue.

Try:

[(ngModel)]="embarqueContenedor?.contenedor?.id"