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