Angular 5和Primeng下拉菜单动态添加和删除选项

时间:2019-01-07 09:09:43

标签: angular typescript angular5 primeng primeng-dropdowns

我致力于角度5和定调。我的项目页面有2个p-dropdown,要求是,如果car dropdown中的标签为'Others',则在第二个下拉列表中添加一个名为'No Paint'的选项,并且如果{{1} }下拉标签不是car从第二个下拉列表中删除'Ohters'选项。我一直在动态地添加和删除下拉菜单选项。谁能指导,下面是我的代码。谢谢

'No Paint'

型号:DropDownOptions.ts

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

我确实尝试过export class DropDownOptions { label: string; value: string } ,但这会在我更改下拉列表值时多次添加“其他”选项。

2 个答案:

答案 0 :(得分:1)

这应该很简单。在第一个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;
}

答案 1 :(得分: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'
}