Akhil Korissery
Akhil Korissery

Reputation: 58

Primeng Multiselect drop down inconsistent behaviour

I am having a primeng multiselect dropdown whose value is changed based on a selection from another dropdown.

<p-dropdown id="test" name="test" [style]="{'width':'100%'}"
 [(ngModel)]="selectedState" [options]="states" (onChange)="getCities()">
    </p-dropdown>

on selection of the above drop down triggers a function getCities() which is a rest end point that fetches the corresponding cities for a state. The cities value is populated on to the below multiselect drop down. The selectedCities may contain already selected values. So if a list of city does not contain any selectedCities the multiselect drop down comes in a weird state .

<p-multiSelect  id="names" name="names" [style]="{'width':'100%'}"
 [options]="cities" [(ngModel)]="selectedCities" (ngModelChange)="onModelChange()">
</p-multiSelect>

Thanks in advance. enter image description here

Upvotes: 0

Views: 4669

Answers (1)

Joosep Parts
Joosep Parts

Reputation: 6235

Problem is that you overwrite selectedCities but you with wish to keep previous selectedCities. selectedCities needs to hold latest cities + previous selections. Let's just update selectedCities on need basis.

Without seeing getCities() it's hard to know what's going on, but I'm guessing it returns data of cities. We flush cities and give it only the current selection.We use concat to add two arrays selectedCities and newdata together. We use spread ... to update the array and trigger template update. We use new Set to make sure we don't add duplicates on cities.

getCities() {
this.cities = this.selectedCities;
this.cities = [...new Set(this.cities.concat(data))];
}
onSelectDeselectCity(event: any) {
if (this.selectedCities.includes(event.value) { // remove
    this.selectedCities.splice(this.selectedCities.indexOf(event.value), 1);
} else {
    this.selectedCities.push(event.value) // add
  }
}
<p-multiSelect  id="names" name="names" [style]="{'width':'100%'}"
 [options]="cities" [(ngModel)]="selectedCities" (ngModelChange)="onSelectDeselectCity($event)">
</p-multiSelect>

Upvotes: 1

Related Questions