Utilizing PrimeNG dropdowns within various p-tree nodes: Distinguishing between selected choices

I am working with a PrimeNg p-tree component

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

The treeNodes are defined using ng-templates, with one template looking like this:

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

In the left menu, there is a menu item that triggers this command -

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

When you click on the menu item, it calls addElement(label: string, type: string), which adds another TreeNode as a child of the root node. The addElement function looks like this:

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

Everything works well so far -- you can add multiple treeNodes with input fields and dropdowns containing the same select options.

https://i.sstatic.net/6PJg8.png

The issue arises when selecting an option in one dropdown, causing the other dropdown to also apply the same selected option. I want to be able to select different options for each dropdown instance.

Can someone help me figure out how to set up the ngModel on p-dropdown to allow for multiple selected 'stage' items?

Thank you

Answer №1

To bind an array using [(ngModel)], each dropdown should be bound to a separate model.

For example:

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

Where the value of i is incremented for each new dropdown.

You can increment i using the following method:

<div *ngFor="let x of array; let i = index; trackBy:trackByIndex">
   control here
</div>

trackByIndex(index: number, obj: any): any { return index; }

The statement let x of array represents your main loop in this context.

Answer №2

Explaining a better approach:

To achieve the desired outcome, it's recommended not to utilize [(ngModel)] as it binds all selected values to one entity. Instead, consider using an onChange event like this:

     <p-dropdown [options]="stages" appendTo="body" (onChange)="onChangeEvent($event.value)" optionLabel="name"></p-dropdown>

You can then define an onChange event function such as:

 onChangeEvent(stage: Stage) {
    console.log("stage.name = " + stage.name);
  }

This way, each dropdown selection will be captured independently by $event.value in the onChange event instead of combining all dropdown values together.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it beneficial to utilize an interface for constructing a class model?

The Interface: export interface IAddEditGeneralDictionary { Code: string; StartDate?: Date | string; FinishDate?: Date | string; Name: string; } The Realization: export class AddEditGeneralDictionary implements IAddEditGe ...

Angular TextInput Components don't seem to function properly when dealing with arrays

I am trying to create a collection of text input components with values stored in an array. However, when using the following code, the values seem to be placed incorrectly in the array and I cannot identify the bug. <table> <tr *ngFor="let opt ...

Right-align the text in the title of the material card

Why isn't the CSS aligning my title of matcard to the right? <mat-card [ngStyle]="{ 'margin':'5px','height':'130px'}"> <mat-card-header> <mat-card-title [ngStyle]="{ 'text-align': ...

Sharing the input value with a service in Angular 4

I am a beginner when it comes to Angular 4. I currently have a variable named "md_id" which is connected to the view in the following way. HTML: <tr *ngFor="let item of driverData"> <td class="align-ri ...

Angular has a built-in function to determine the next ID after deletion of some items

I am currently facing a situation where I have a list of contacts in a detailed view and navigating through them using the following code: <nav> <a [routerLink]="['/details', friend.id - 1 ]" *ngIf="!(friend.id == 1)"> P ...

Error encountered with the root reducer due to data type mismatch

Within my Redux store setup, I have a persistedReducer initialized to include the redux-persist config and the "rootReducer": client/src/redux/store.ts: import { configureStore } from '@reduxjs/toolkit'; import { persistStore, persistReducer } f ...

Failing to reach the nested if statements within a switch case block

Before removing my question, please read this. Despite testing with console.logs, my code does not enter the if statements. I have not come across a similar solution to my issue. In an attempt to address any timing or asynchronous problems, I added a use ...

Error Encountered: White screen issue affecting Ionic 6 / Angular 14 app running on Android 6.1 device without Google Mobile

After successfully deploying my new Ionic 6 / Android 14 app on multiple devices, I encountered a problem with one specific device - a Zebra ET50 running Android 6.1 without Google Mobile Services. The app fails to load and only shows a white screen. I no ...

When using Observables in AngularFire2, the $ref property does not get captured

Recently, I started working with AngularFire2 (version 4.0.0-rc.1) and encountered a challenge that has me stuck: getWishlist$(): FirebaseListObservable<{}> { return <FirebaseListObservable<{}>>this.store.select(getFirebaseUID) ...

After upgrading from Angular 13 to 14, the <app-root> component is failing to load. Despite no noticeable changes, the issue persists

Having upgraded my Angular 13 app to version 14, I encountered an issue where the page no longer loads properly. Despite checking the configuration and stripping down the index.html file to its basics, the issue persists - nothing seems to be working. Upo ...

Tips for sending data in Angular 8's Http GET method within a service class, especially when the backend requires a dictionary format

I am working on a C# backend with an HttpGet method that is expecting a dictionary as request parameters. public async Task<IActionResult> Search([BindRequired, FromQuery] IDictionary<string, object> pairs) Currently, my frontend is built in A ...

The Route.ts file does not export any HTTP methods

Encountering an error while trying to migrate code from Next JS 12 with pages router in Javascript to Next JS 13 with TypeScript. ⨯ Detected default export in 'vibe\src\app\api\auth[...nextauth]\route.ts'. Export a name ...

What is the reason for not hashing the password in this system?

My password hashing code using Argon2 is shown below: import { ForbiddenException, Injectable } from '@nestjs/common'; import { PrismaService } from 'src/prisma/prisma.service'; import { AuthDto } from './dto'; import * as arg ...

What is the best approach in Typescript to ensure type understanding when importing using require()?

Currently, I am working with TypeScript within IntelliJ. Let's say I have the following code: const functions = require('firebase-functions'); Then I proceed to use it in this manner: exports.doSomething = functions.https.onCall((data, c ...

When in production mode, parameter routing and conditions do not function as expected

I have a straightforward routing setup like the following: import { NgModule } from '@angular/core'; import { PreloadAllModules, RouterModule, Routes } from '@angular/router'; const routes: Routes = [ { path: 'scenario', ...

Blend Mode / Vue CLI / Remote server routing

I'm looking for a solution to set up a proxy in an AngularCLI/Webpack environment. The main goal is to forward requests from http://localhost:4200/rest to https://someserver.com/somepath/rest. One challenge is that the endpoint is using HTTPS instead ...

The specified class is not found in the type 'ILineOptions' for fabricjs

Attempting to incorporate the solution provided in this answer for typescript, , regarding creating a Line. The code snippet from the answer includes the following options: var line = new fabric.Line(points, { strokeWidth: 2, fill: '#999999', ...

Position your content on the right side of the Angular Material tabs

I'm struggling with positioning content next to the tabs on the right side. I attempted placing content in a disabled mat-tab, but I don't want the content (located on the right) to be disabled. In addition, the content includes a dropdown menu ...

Vue composable yields a string value

I am currently using a Vue composable method that looks like this: import { ref } from 'vue'; const useCalculator = (num1: number, num2: number, operation: string) => { const result = ref(0); switch (operation) { case 'add& ...

Encountered a CORS error while attempting to make a request within my Heroku-hosted application

I faced this issue previously when making requests in localhost, and was able to resolve it by configuring a proxy in Angular. Due to using a custom proxy, I had to remove the configuration from my Angular app before deploying it on Heroku. Failing to do ...