【问题标题】:Angular 5 and Primeng dropdown add and remove option dynamicallyAngular 5 和 Primeng 下拉列表动态添加和删除选项
【发布时间】:2019-01-07 09:09:43
【问题描述】:

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

    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')),但添加“其他”选项的次数与我更改下拉值的次数一样多。

【问题讨论】:

  • 请创建 stackblitz 链接
  • @Justcode 很抱歉,它在我的组织中被阻止。
  • 尝试任何在线创作者,尝试 codpen

标签: angular typescript angular5 primeng primeng-dropdowns


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2020-07-11
      • 2021-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多