Ng-select: MultiSelect Two way bind

Created on 11 Oct 2017  路  4Comments  路  Source: ng-select/ng-select

I Would like to set the value/ add a tag after the component has been instantiated. I currently have my code looking like this,

<ng-select
                [items]="accounts"
                bindLabel="currency"
                bindValue="id"
                [multiple]="true"
                [(ngModel)]="selectedAccounts">
        </ng-select>
<button (click) = "setModel()" class="btn btn-secondary btn-sm"> Set INR</button>

Component :

accounts = [
    {id: 0, currency: 'INR'},
    {id: 1, currency: 'USD'},
    {id: 2, currency: 'GBP'},
    {id: 3, currency: 'EUR'},
    {id: 4, currency: 'CSE'},
  ];

 setModel() {
    // logic to find if the the selected account is already present and if not,
  this.selectedAccounts.push(0);
  }

Expected behaviour

INR should be added as a tag in the drop down.

Actual behaviour

It does not listen to changes made in the selectedAccounts programatically, even if it is two way bound.

More Info

What works is this... I have to re assign a new array every time i need to bind something from the component to the view

let selectionAray: any[] = this.selectedAccounts.slice(0);
selectionAray.push(0);
this.selectedAccounts = selectionAray;

Most helpful comment

Hi, in my latest pr #77 I updated readme about change detection. Current behaviour works by design and here is the reasoning:

Change Detection

Ng-select component implements OnPush change detection which means the dirty checking checks for immutable
data types. That means if you do object mutations like:

this.items.push({id: 1, name: 'New item'})

Component will not detect a change. Instead you need to do:

this.items.push({id: 1, name: 'New item'})
this.items = [...this.items];

This will cause the component to detect the change and update. Some might have concerns that
this is a pricey operation, however, it is much more performant than running ngDoCheck and
constantly diffing the array.

All 4 comments

Hi, in my latest pr #77 I updated readme about change detection. Current behaviour works by design and here is the reasoning:

Change Detection

Ng-select component implements OnPush change detection which means the dirty checking checks for immutable
data types. That means if you do object mutations like:

this.items.push({id: 1, name: 'New item'})

Component will not detect a change. Instead you need to do:

this.items.push({id: 1, name: 'New item'})
this.items = [...this.items];

This will cause the component to detect the change and update. Some might have concerns that
this is a pricey operation, however, it is much more performant than running ngDoCheck and
constantly diffing the array.

Thanks for the explanation.. That works

Ah.. Thanks mate! 馃憤

Was this page helpful?
0 / 5 - 0 ratings