Angular 5和Primeng下拉列表动态添加和删除选项



我研究角度5和primeng。我的项目页面有 2 个p-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'}
            ];

模型: 下拉选项.ts

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

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

这应该很简单。添加第一个 p 下拉列表(汽车)事件(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;
}

我使用 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'
}

最新更新