0

我在 angular 5 和primeng 上工作。我的项目页面有 2p-dropdown并且要求是,如果标签中的标签car dropdown'Others'添加'No Paint'在第二个下拉列表中命名的选项,并且car下拉标签不是从第二个下拉列表'Ohters'中删除'No Paint'选项。我被困在动态添加和删除下拉选项中。任何人都可以请指导,下面是我的代码。谢谢

    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'}
            ];

模型:DropDownOptions.ts

export class DropDownOptions {
label: string;
value: string
}

我确实尝试this.cars.push(new DropDownOptions('Others', 'others'))过,但这会在我更改下拉值时多次添加“其他”选项。

4

2 回答 2

1

这应该很简单。添加第一个 p-dropdown (car) 事件(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;
}
于 2019-01-07T09:47:59.677 回答
0

我使用 ES6 执行此操作,如下所示:

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{
this.paints = this.paints.filter(e => e !== 'Others') //remove 'Others'
}
于 2019-01-07T10:25:48.740 回答