I'm using PrimeNG 15
with Angular 14
. I have two multiselect dropdowns. The options for dropdown 1 (source city) come from list 1, and the options for dropdown 2 (destination city) come from list 2. The requirement is that the source city and destination city must not be the same. Therefore, I want the city selected in dropdown 1 to be excluded from the options in dropdown 2. My code looks like this:
<p-dropdown
[options]="sourceCities"
[(ngModel)]="selectedSourceCity"
optionLabel="name">
</p-dropdown>
<p-dropdown
[options]="destinationCities"
[(ngModel)]="selectedDestinationCity"
optionLabel="name">
</p-dropdown>
constructor() {
this.sourceCities = [
{name: 'New York', code: 'NY'},
{name: 'Rome', code: 'RM'},
{name: 'London', code: 'LDN'},
{name: 'Istanbul', code: 'IST'},
{name: 'Paris', code: 'PRS'}
];
this.destinationCities = [
{name: 'New York', code: 'NY'},
{name: 'Rome', code: 'RM'},
{name: 'London', code: 'LDN'},
{name: 'Istanbul', code: 'IST'},
{name: 'Paris', code: 'PRS'}
];
}
I tried creating a pipe:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'excludeValue'
})
export class ExcludeValuePipe implements PipeTransform {
transform(value: any, args?: any): any {
return value.filter(function (item) {
console.log(args)
return item.id != args;
});
}
}
There are two problems with my pipe: 1.) It doesn't work for multiple values. 2.) I don't know how to use a pipe on a PrimeNG dropdown.
Please feel free to suggest any other approach without using pipe.
I'm not getting any answers on Google. Please help.
CodePudding user response:
Your final requirements were as follows:
- The selected
sourceCity
shall not be selectable asdestinationCity
- The selected
destinationCity
shall not be selectable assourceCity
- No initial value shall be selected
I would propose the solution below.
First the ts-part:
cities: City[];
selectedSourceCity: City;
selectedDestinationCity: City;
constructor() {
this.cities = [
{name: 'New York', code: 'NY'},
{name: 'Rome', code: 'RM'},
{name: 'London', code: 'LDN'},
{name: 'Istanbul', code: 'IST'},
{name: 'Paris', code: 'PRS'}
];
}
get filteredSourceCities() {
return this.cities.filter(c=> c.code !== this.selectedDestinationCity?.code);
}
get filteredDestinationCities() {
return this.cities.filter(c=> c.code !== this.selectedSourceCity?.code);
}
Then the html-part:
<h5>Source City</h5>
<p-dropdown [options]="filteredSourceCities"
[(ngModel)]="selectedSourceCity"
[autoDisplayFirst]="false"
optionLabel="sourceCity">
</p-dropdown>
<h5>Destination City</h5>
<p-dropdown [options]="filteredDestinationCities"
[(ngModel)]="selectedDestinationCity"
[autoDisplayFirst]="false"
optionLabel="destinationCity">
</p-dropdown>
By setting [autoDisplayFirst]="false"
, no initial value is selected.