I work on angular 5 and primeng. My project page has 2 p-dropdown
's and requirment is, if the label in car dropdown
is 'Others'
add an option named 'No Paint'
in the second dropdown and if car
dropdown label is not 'Ohters'
remove 'No Paint'
option from second dropdown. I am stuck in adding and removing the dropdown options dynamially. Can anyone please guide, below is my code. Thanks
Car: <p-dropdown [options]="cars" [(ngModel)]="selectedCar" [filter]="true"></p-dropdown>
<p-dropdown [options]="paints" [(ngModel)]="selectedPaint" [filter]="true"></p-dropdown>
constructor() {
this.cars= [
{name: 'AA', code: 'aa'},
{name: 'BB', code: 'bb'},
{name: 'CC', code: 'cc'},
{name: 'DD', code: 'dd'},
{name: 'Others', code: 'others'}
];
this.paints= [
{name: 'XX', code: 'xx'},
{name: 'YY', code: yyb'},
{name: 'ZZ', code: 'zz'}
];
Model: DropDownOptions.ts
export class DropDownOptions {
label: string;
value: string
}
I did try this.cars.push(new DropDownOptions('Others', 'others'))
but this is adding 'Others' option as many times as I change dropdown values.
This should be quite simple. Add on first p-dropdown (car) event (onChange)
<p-dropdown [options]="cars"
(onChange)="checkIfOther($event)"
[(ngModel)]="selectedCar"
[filter]="true"></p-dropdown>
.ts:
checkIfOther(event){
if(event.value.code === 'others'){
this.paints.find(paint => paint.code == 'No Paint') === undefined ? this.paints.push({name:'No paint', code: 'No Paint'}) : null;
}
else{
let idx = this.paints.findIndex(paint => paint.code == 'No Paint';
idx != undefined ? this.paints.slice(idx,1) : null;
}