Issues with PrimeNG listbox functionality in Angular 2

In my reactive form, there are two controls. One control is a dropdown for selecting a country, and the other control is a list of checkboxes for selecting cities within the chosen country. The issue arises when I use primeNg's listbox for the city selection. The problem I face is that once I select one city, all other cities get selected as well. Additionally, there seems to be a problem with null values appearing in the second control even after selecting cities.

import { Component } from '@angular/core';
import { SelectItem } from 'primeng/primeng';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: 'app/app.template.html'
})
export class AppComponent {

    countryForm : FormGroup;

    countries: Country [] ;

    constructor(public fb: FormBuilder) { 
       this.countries = [
        {name:'USA', continent:'North America', cities :[
           {name: 'New York'} , { name: 'Los Angeles'} 
          ]},
        {name:'UK', continent:'Europe', cities :[
           {name: 'London'} , { name: 'Manchester'} , { name: 'Cambridge'} ,  { name: 'Bristol'}
          ]},
        {name:'Philippines', continent:'Asia', cities :[
           {name: 'Manila'} , { name: 'Davao'} , { name: 'Cebu'}
          ]},
         {name:'Japan', continent:'Asia', cities :[
           {name: 'Tokyo'} , { name: 'Kyoto'} , { name: 'Yokohama'}
          ]},
      ]
    }

    listOfCities: City [];

    ngOnInit() {
      this.countryForm= this.fb.group({
        selectedCountry:null,
        selectedCities: null
      });
      this.countryForm.controls['selectedCountry'].valueChanges.subscribe(
        value => {
          if(this.countryForm.controls['selectedCountry'].value!=null){
            this.listOfCities = this.countryForm.controls['selectedCountry'].value.cities;
          }
          else{
            this.listOfCities = [];
          }
      });
    }

    resetCountrySelection(){
      this.countryForm.controls['selectedCountry'].setValue(null);
      this.countryForm.controls['selectedCities'].setValue([]);

    }
}

You can view the plunkr example here

Answer №1

Make a modification here:

inside component.ts file

listOfCities: SelectItem [];

ngOnInit() {
  this.countryForm= this.fb.group({
    selectedCountry:null,
    selectedCities: null
  });
  this.countryForm.controls['selectedCountry'].valueChanges.subscribe(
    value => {
      if(this.countryForm.controls['selectedCountry'].value!=null){
        this.listOfCities = this.countryForm.controls['selectedCountry'].value.cities.map((v)=>{return {label:v.name, value:v.name} });
      }
      else{
        this.listOfCities = [];
      }
  });
}

convert the data from listOfCities to an array of SelectItems and use the map function on cities to format them as {label:, value:}. Update the template like this:

<p-listbox [options]="listOfCities" formControlName="selectedCities" [(ngModel)]="countries1" multiple="multiple" checkbox="checkbox" [style]="{'margin-top':'10px','min-height':'500px','width':'100%','max-height':'500px'}" >
        <template let-city pTemplate="body">
          <span style="font-size:12px;">{{city.label}}</span>
        </template>
      </p-listbox>

and declare an array of strings:

countries1: string[]; // selected city 

In the template add this

[(ngModel)]="countries1"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: The service object is unable to bind to ngModel in Angular 5 due to a TypeError, as it cannot read the property 'state' of undefined within Object.eval

Within my service, I have an object declared: public caseDetails = { partyId: '', address: { state: '', city: '', zip: '', street: '' } } I am trying to bind these objects to i ...

Customize your Loopback 4 OpenAPI with NSWAG by making filters optional and specifying data types

I am encountering an issue with the Loopback 4 filter on the generated endpoints being marked as required in my Nswag typescript file. I need it to be optional, but I am struggling to locate where this requirement is originating from. The endpoint from my ...

What is the reason behind the command "npm-install" placing files directly into the root directory?

After pulling my front-end project from the repository, I noticed that the node_modules folder was missing. My usual approach is to use npm install to get all the dependencies listed in the package.json file installed. However, this time around, I ended u ...

Assigning union values to an object array: a guide for Typescript

When working with union typed values in an object array, how should the setState() function be implemented? enum SomeStateEnum { IsRunning, Name, } type PersonState = { [SomeStateEnum.IsRunning]: boolean; [SomeStateEnum.Name]: string; }; const st ...

Creating a Circle with Pixi.js v4 and Typerscript in IONIC 2

I have been attempting to create a custom class in TypeScript that utilizes PIXI.js to draw circles. Below is the code for my home.ts class: import { Component, ViewChild, ElementRef } from '@angular/core'; import { NavController } from 'i ...

Unable to link with 'NgModel' as it is not recognized as a valid property of 'ion-input'

I'm experiencing some difficulty with the following error message: Error: Uncaught (in promise): Error: Template parse errors: Can't bind to 'NgModel' since it isn't a known property of 'ion-input'. 1. If 'ion-input ...

What is the best way to store a small number of files in the state

I have recently implemented Drag and Drop functionality, and now I am facing an issue where I need to save a few files in state. const [uploadedFiles, setUploadedFiles] = useState<any[]>([]); const onDropHandler = async (e: React.DragEvent<HTMLDi ...

Is it feasible to utilize mat-selection-list with an object instead?

I've been exploring the mat-selection-list feature available in the material.angular.io documentation at material.angular.io/components/list/overview Instead of using a string array, I'm aiming to utilize an array of objects. The documentation c ...

Display a loading spinner while refreshing a list

Currently, I am in the process of developing an app using React Native. My goal is to display information (text) below my CalendarList based on data stored in an array. One of the properties in the array is the date. To achieve this, I have created a filte ...

The 'changes' parameter is inherently defined with an 'any' type.ts(7006)

Encountering an error and seeking help for resolution. Any assistance would be highly appreciated. Thank you. Receiving this TypeError in my code. How can I fix this issue? Your guidance is much appreciated. https://i.sstatic.net/cWJf4.png ...

Why isn't my event handler triggering when working with TypeScript services and observables?

I am currently working on a project in Angular 2 where I am incorporating observables and services in typescript. However, I have encountered an issue where the event handler in my observable is not being triggered. Below is the code snippet: The Service ...

Issues arise with transferring React component between different projects

My goal is to develop a React component that serves as a navigation bar. This particular component is intended to be imported from a separate file into my App.js. Currently, the component is designed to simply display a 'Hello world' paragraph, ...

Angular 4: The parameter 'typeof CLASS' cannot be assigned to the parameter 'INTERFACE'

Exploring dynamic components in Angular has been quite interesting for me. However, I've encountered a roadblock that I'm unsure how to overcome. This is the interface I am working with: export interface InjectableComponent{ setData(data: a ...

Spring Boot - The Ultimate Guide to Hosting Angular2 Compiled Files

Currently, I am using a Spring Boot restful server alongside an Angular2 front-end application. In an attempt to streamline the process, I have been trying to host the front-end files on Tomcat in order to avoid serving them separately. Unfortunately, desp ...

Testing the API client against a remote API with constantly changing endpoints

Imagine I'm developing an API client for a complex API that is constantly changing and unreliable. I want to test this client using Jest, but I prefer to test it against a snapshot of the API response rather than the live API. However, I don't wa ...

The parameter must be of type 'string', but you are attempting to assign a 'Promise<any>'

Starting a React App requires fetching the user's information from localStorage and initiating a socket connection with the server based on the user's id. However, when trying to pass the user's id to the socket function, TypeScript throws ...

A series of functions with designated return types passed to the subsequent function

I have a vision to craft an innovative array that is filled with functions. const a = [ (): { a: string } => ({ a: 'alpha'}), ({ a }): { b: string } => ({ b: 'beta' }), ({ a, b }): {} => ({}), ] The functions are speci ...

Issue loading AngularJS 2 RC5 form is encountered

This issue with the form is really bothering me. Here is my package.json: "dependencies": { "@angular/common": "2.0.0-rc.5", "@angular/compiler": "2.0.0-rc.5", "@angular/core": "2.0.0-rc.5", "@angular/forms": "0.3.0", "@angular/http ...

The modeless service in FeathersJS is failing to provide the correct JSON response

Could someone please explain to me how the service creation process works? I have been struggling for hours trying to receive JSON objects that do not meet my expectations. After much trial and error, I have come up with the following code for the before h ...

How to efficiently store and manage a many-to-many relationship in PostgreSQL with TypeORM

I have a products entity defined as follows: @Entity('products') export class productsEntity extends BaseEntity{ @PrimaryGeneratedColumn() id: number; //..columns @ManyToMany( type => Categories, categoryEntity => cat ...