Search code examples
angularprimengprimeng-dropdowns

Values are not populating in multiselect dropdown values based on another multiselect dropdown PrimeNg


I have two multiselect dropdowns as given below. If I choose

  • First dropdown :"ASIA" then Second dropdown should populate values: "India" and "UAE"
  • First dropdown :"ASIA" and "EUROPE" then Second dropdown should populate values: "India", "UAE" and "Germany"

I have tried the below code and the values are not populating in second dropdown when I select value form first. Second dropdown is empty always.

First multiselect dropdown :-

<p-multiSelect (onChange)="updateSecondDropdown($event)" [options]="regions" [(ngModel)]="regionValues" optionLabel="name" optionValue="name" defaultLabel="Select Regions"></p-multiSelect>

Second multiselect dropdown :-

<p-multiSelect [options]="countries" [(ngModel)]="countryValues" optionLabel="name" optionValue="name" defaultLabel="Select Countries"></p-multiSelect>

Typescript code :-

countries:any[]=[];

regions:any[]=[
  {id:1, name:"ASIA"},
  {id:2, name:"EUROPE"},
  {id:3, name:"NORTH AMERICA"},
  {id:4, name:"SOUTH AMERICA"},
]


countriesMapping:any[]=[
  {id:1, region:"ASIA", name:"India"},
  {id:2, region:"ASIA", name:"UAE"},
  {id:3, region:"NORTH AMERICA", name:"United States"},
  {id:4, region:"NORTH AMERICA", name:"Canada"},
  {id:5, region:"SOUTH AMERICA", name:"Mexico"},
  {id:6, region:"EUROPE", name:"Germany"}
]


updateSecondDropdown(event){
  this.countries=[];
  let selectedRegions = event.values;
  let selectedRegionNames = selectedRegions.map(o => o.name);
  selectedRegionNames.forEach((region) => {
   this.countriesMapping.forEach((country, index) => {
    if(country.region===region)
       this.countries.push(this.countriesMapping[index]);
   });
  });
}

I am using PrimeNg version: 8.0.0


Solution

  • This solved my problem

    updateSecondDropdown(event) { 
       const selectedRegions = event.value; this.countries = 
       this.countries = this.countriesMapping.filter((country) => {
         return selectedRegions.some(region => region.name===country.region)
       }); 
    }