Search code examples
angulartypescriptprimengprimeng-dropdowns

PrimeNg dropdown in multiple p-tree nodes: Differentiating selected options


I have a PrimeNg p-tree

    <p-tree [value]="treeNodes" selectionMode="single" [(selection)]="selectedNode"></p-tree>

TreeNodes are expressed with ng-templates, one of the templates being as follows.

    <ng-template let-node pTemplate="stagebased" >
        <input [(ngModel)]="node.label" type="text"  >
        <p-dropdown [options]="stages"  [(ngModel)]="stage"  optionLabel="name"></p-dropdown>
   </ng-template>

There is a menu on the left which has a menu item with this command -

command: (event) => { this.addElement("<Node Label>", "stagebased") }

So you click a menu item and that calls addElement(label: string, type: string), which adds another TreeNode as a child of the root node. addElement is follows:

addElement(label: string, type: string) {
    var node =
    {
      label: label,
      type: type
    };
    this.selectedNode = this.treeNodes[0];
    this.selectedNode.children.push(node);
  }

All good so far -- you can click addElement multiple times to add multiple treeNodes containing input fields and dropdowns with the same select options available.

enter image description here

The problem is if I select an option in one dropdown - the other dropdown applies the same option selected. I cannot select a different option for one dropdown instance as opposed to another.

How do I express the ngModel on p-dropdown in a way that allows for multiple selected 'stage' items?

Thanks


Solution

  • You can bind [(ngModel)] to an array. Each dropdown needs to be bound to a separate model.

    So something like:

    [(ngModel)]="selectedStages[i]"

    Where i is being incremented for each new dropdown.

    You should be able to use something like the following to increment i:

    <div *ngFor="let x of array; let i = index; trackBy:trackByIndex">
       control here
    </div>
    
    trackByIndex(index: number, obj: any): any { return index; }
    

    let x of array here would be whatever your main loop is going to be.