Declined
Last Updated: 16 Apr 2019 12:12 by ADMIN
Travis
Created on: 09 Apr 2019 15:02
Category: DropDownList
Type: Bug Report
0
Selected item in dropdownlist not set correctly after sorting bound data

In the example below "X-Small" is initially the selected item in the dropdown.  Once you click the "Sort" button and sort the array, "2X-Large" becomes the highlighted item in the dropdown but "X-Small" is displayed.  I would expect that "X-Small" would be highlighted.  After opening and closing the dropdown "2x-Large" becomes the selected item even if you don't select it.  The same behavior does not happen with a simple select dropdown.

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
  <form>
    <div>
      <p>T-shirt size:</p>
      <kendo-dropdownlist [data]="listItems" [(ngModel)]="selectedShirt" name="shirtsize">
      </kendo-dropdownlist>
    </div>
    <br/>
    <div>
    <select [(ngModel)]="selectedShirt" name="shirtsize2">
      <option *ngFor="let d of listItems">{{d}}</option>
    </select>
    </div>
    <br/>
    <button (click)="sortArray()">Sort</button>
  </form>
  `
})
export class AppComponent implements OnInit {
    public listItems: Array<string> = ["X-Small", "Small", "Medium", "Large", "X-Large", "2X-Large"];
    public selectedShirt: string;
    ngOnInit(){
      this.selectedShirt = this.listItems[0];
    }

    sortArray(){
      this.listItems.sort((a, b) => a.localeCompare(b));
    }
}

1 comment
ADMIN
Svet
Posted on: 16 Apr 2019 12:12
Hi Travis,

Thank you for the feedback.

The undesired behavior is caused due to Angular's change detection not being triggered. In order to trigger it properly we need to assign a new reference to the listItems array, which will cause the component to be re-rendered. This could be achieved using the generic JavaScript slice() method:
this.listItems = this.listItems.sort((a, b) => a.localeCompare(b)).slice();

Check the following updated example:
https://stackblitz.com/edit/angular-mmvzu1-tm3s9b?file=app/app.component.ts

Let us know in case any further feedback is required for this case.

Regards,
Svetlin
Progress Telerik
Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.