Multiselect not working when array is initialized

Viewed 51

I am using primeng Multiselect, I have written some logic to push data based on search value from backend, for pushing element we have to initialize it first, other it gives me an error of push of undefined, but when I am using by initializing dropdown's array variable, it doesn't showing me the data which I got from API.

On the other hand when I am not initializing the dropdown data variable, and directly assigning data which I got from API then it is working,

I am attaching the stackblitz link where I am facing issue:

https://stackblitz.com/edit/primeng-multiselect-demo-qykbzn?file=src%2Fapp%2Fapp.component.ts

this is working code when I am not initializing it

dropdownData;

    getCountryData(countryName: string) {
        const url = 'https://restcountries.com/v3.1/name';
        this.http
            .get(`${url}/${countryName}?fullText=true`)
            .pipe(debounceTime(20000))
            .subscribe((data) => {
                this.dropdownData = data.map((item) => ({
                    ...item,
                    countryName: item.name.common,
                    code: item.fifa
                }));

                // if (localDropdownData.length) {
                //  localDropdownData.forEach((element) => {
                //      this.dropdownData.push(element);
                //  });
                // }
                console.log('data', this.dropdownData);
                this.cd.detectChanges();
            });
    }
1 Answers

Try change the value assignment from

   localDropdownData.forEach((element) => {
     this.dropdownData.push(element);
   });

to

   this.dropdownData=[...localDropdownData];

array.push does not change the variable reference, hence it is not picked up by angular change detection.

Related