我有一个带有两个控件的反应形式。一个控件是选择国家/地区的下拉菜单。另一个控件是一个复选框列表,用于选择所选国家/地区的城市。我在最后一个控件(城市选择)中使用了primeNg的列表框。现在,我在使用primeng列表框时遇到问题。问题是,一旦我选择了一个城市,所有其他城市也被选中。即使有选定的城市,我也会在表格的第二个控件(城市选择)中得到一个空值。
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([]);
}
}
这是plunkr http://plnkr.co/edit/yO4mNQveTyJgsvF9wUFE?p=preview
答案 0 :(得分:0)
改变这个:
在component.ts
中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 = [];
}
});
}
将listOfCities转换为数组SelectItem并将函数映射应用于城市并将{label:,value:}放入模板更改中:
<p-listbox [options]="listOfCities" formControlName="selectedCities" [(ngModel)]="coutries1" 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>
并创建字符串数组:
coutries1: string[]; // selected city
模板中的放了这个
[(ngModel)]="coutries1"