angular2 multi-select update data not working in an array

Hi! In this article, we learn something trick in angular. Sometimes angular 2 multi-select does not update after pushing the new data into the array.

Let’s have an example :
I had a dropdown list of country, I need to add a new country to the dropdown list.

this.dropdownList = [ { “id”: 1, “itemName”: “India” }, { “id”: 2, “itemName”: “Singapore” }, { “id”: 3, “itemName”: “Australia” }, ]

I need to add Canada to this list. So EveryOne did the same logic was to push data into an array using push() method in javascript. Like

this.dropdownList.push({id:4, itemName: ‘Canada’})

That’s fine. But sometimes this push method not update in your dropdown list. It’s not shown to your front end.

Let see a solution to such a situation. What I suggest just clone the old data and empty the current and reassign it to the list.

let cloner = […this.dropdownList]; this.dropdownList = []; // It may need or not need. this.dropdownList = cloner;

angular 2 multi-select: HTML5

angular 3 multi-select: .ts file

export class AppComponent { dropdownList = []; selectedItems = []; dropdownSettings = {}; ngOnInit() { this.dropdownList = [ { “id”: 1, “itemName”: “India” }, { “id”: 2, “itemName”: “Singapore” }, { “id”: 3, “itemName”: “Australia” }, ] this.dropdownSettings = { singleSelection: false, text: “Select Countries”, selectAllText: ‘Select All’, unSelectAllText: ‘UnSelect All’, enableSearchFilter: true, classes: “myclass custom-class” }; } onItemSelect(item: any) { console.log(item); console.log(this.selectedItems); } OnItemDeSelect(item: any) { console.log(item); console.log(this.selectedItems); } onSelectAll(items: any) { console.log(items); } onDeSelectAll(items: any) { console.log(items); } addCountry(){ this.dropdownList.push({id: 4, itemName: ‘Canada’}) } }

I hope this will helpful to you. Thank you for reading. If you like this please comment below. It will encourage me.