p-dropdown not displaying selected values in reactive forms

I am struggling with binding my object to the dropdown in primeng. The dropdown is populating with empty items and I can't figure out how to specify the field name.

HTML

<div class="form-group col-xs-3 col-md-3"
                                     [ngClass]="{
                                     'has-error':((ersaForm.get('costCenter').touched || ersaForm.get('costCenter').dirty ) && 
                                      !ersaForm.get('costCenter').valid) || (ersaForm.get('costCenter').value.cost_center_name == '')
                                     }">
 <label for="costCenterId" class="control-label">Cost Center</label>
 <p-dropdown [options]="iCostCenter" styleClass="form-control" formControlName="costCenter" placeholder="Cost Center (required)" id="costCenterId" name="costCenter"  dataKey="cost_center_id">
</p-dropdown>

object

    {
  "result": [
    {
      "cost_center_id": 0,
      "cost_center_name": "0"
    },
    {
      "cost_center_id": 1,
      "cost_center_name": "1"
    },
    {
      "cost_center_id": 2,
      "cost_center_name": "2"
    },
}

TS

    export interface ICostCenter{

        cost_center_id: string,
        cost_center_name: string
    }

   iCostCenter: ICostCenter[];
    this._appParams.getAllCostCenters()
            .subscribe(
            data => {
                this.iCostCenter = data.result;

            }

Answer №1

Upon reviewing the official documentation, it stipulates that the utilization of the optionLabel property is necessary when binding to a collection of diverse objects.

<p-dropdown [options]="iCostCenter" optionLabel="cost_center_name" styleClass="form-control" formControlName="costCenter" placeholder="Cost Center (required)" id="costCenterId" name="costCenter"  dataKey="cost_center_id">
</p-dropdown>

Answer №2

<p-dropdown [options]="iCostCenter" 
  optionLabel="cost_center_name" 
  styleClass="form-control" 
  formControlName="costCenter" 
  placeholder="Cost Center (required)" 
  id="costCenterId" 
  name="costCenter"
  dataKey="cost_center_id" 
  optionValue="costCenter">
</p-dropdown>

You have the ability to use the optionValue attribute to assign a specific value to the formControl, instead of relying on the Object.dataKey property which is utilized to uniquely identify a value within the options.

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

Can one invoke ConfirmationService from a different Service?

How can I declare an application-wide PrimeNG dialog and display it by calling ConfirmationService.confirm() from another service? Below is the HTML code in app.component.html: <p-confirmDialog [key]="mainDialog" class="styleDialog" ...

Is the Angular Tutorial's use of the In-memory Web API conforming to the appropriate PUT semantics?

As I was going through the Angular tutorial, I came across the utilization of the In-memory Web API. Everything seems fine except for the segment of code within the PUT heroes method that makes me a bit uneasy. Take a look at it: private heroesUrl = &apo ...

Prevent redirection when submitting and show an error message instead

I implemented a login system where, upon entering the correct username and password, a token is stored in local storage. If there's an error with the credentials, an "Login Unsuccessful" message is displayed. Everything was functioning correctly until ...

The DynamicScript HTTPClient and Observing Elements

I am currently facing an issue while trying to make a GET request using HttpClient in Angular. I want the result to be returned as an Observable. The problem arises when HttpClient does not send the request to the server unless I use the subscribe method. ...

Anticipating the desired data types for Jasmine arguments

Lately, I've been in the process of upgrading my Angular version from 10 to 13 in order to utilize TypeScript 4.6. However, during this upgrade, I made some errors with types in my tests and I'm wondering if others have encountered similar issues ...

Using Jest functions as object properties results in undefined behavior

I am faced with a challenge in my class where I need to mock an object along with its properties intercept(context: ExecutionContext) { const response = contect.switchToHttp().getResponse() // the chain that needs to be mocked if (response.headersSent ...

Converting numbers to strings based on locale in React Native

I have a quantity that, when using the amount.toFixed() function, produces the string "100.00". I would like this result to be formatted according to the specific locale. For example, in Italian the desired output is 100,00, while in English it should be ...

When invoking mongoose.connect(uri, ConnectOptions), the function might not be able to identify some options like useNewUrlParser

Check out my GitHub repository at: https://github.com/safiullah7/legan Working on branch: redux Currently following this tutorial for building a REST API with Node.js, TypeScript, and MongoDB: , but facing an issue connecting to MongoDB. Here is the snip ...

Can I leverage getStaticProps and getStaticPaths within a page component that employs dynamic routing without prior knowledge of the IDs?

I have created a fully static site generation (SSG) app where the backend cannot be accessed during build time. All the data is specific to user permissions, so I cannot specify paths in the getStaticPaths method required for dynamic routed components us ...

Updating directives is required when there is a modification in the input

I created a custom directive that controls the opacity of an element based on an input value: import { Directive, ElementRef, HostListener, Input, OnInit } from '@angular/core'; import { Observable, Subscription } from 'rxjs/Rx'; @Dir ...

Upgrade the current version of Angular2 PrimeNG from 1.1.4 to the latest version available

As a newcomer to angular2, I am looking for guidance on how to update my current version (1.1.4) to the latest one! Currently, I am using version 2.0.0-rc.5 of Angular2. I have attempted to update by running: npm install primeng --save However, despite ...

Ensuring multiple choices are validated within a reactive form in Angular

Having just started working with Angular, I encountered an issue regarding the validation of a user's gender. The default setting for gender is not specified in the form, which is used to update user data. In some cases, the user may choose to set the ...

Library for manipulating SVG elements using Typescript

After experimenting with Raphael and Snap in my Angular 4 app, I've found that neither of them fully support TypeScript. Does anyone happen to know of a library that offers complete TypeScript type support for easy integration with Angular 2/4/5 witho ...

Encountering build issues in my next.js application post updating to version 12.#.# and implementing Typescript

In my next.js application, I recently upgraded to version 10 and added TypeScript to the mix. Despite ironing out all issues during development, I encountered errors when running yarn next build due to my use of the keyword interface. ./src/components/ ...

ng-touched remains unchanged after calling .markAsUntouched on a Custom Control

Editing a field in an Angular 2 form with a custom control and resetting it using .markAsUntouched does not remove the ng-touched class. The sample form structure is as follows: <form #editForm="ngForm"> <input [(ngModel)]="title" name="titl ...

Unlocking Specific URLs in Angular for Data Retrieval

I need assistance setting up a referral system for my angular website. Currently, my website is a single component accessible at localhost:4200. I would like to allow users to enter referral codes when accessing the site, such as 'localhost:4200/r/h7G ...

My instance transforms with the arrival of a JSON file

I'm grappling with a query about data types in TypeScript and Angular 2. I defined a class in TypeScript export class product{ public id:number; public name:string; public status:boolean; constructor(){} } and I initialize an instanc ...

The property 'item' is not found within the specified type 'IntrinsicAttributes & RefAttributes<Component<{}, any, any>>'. Error code: 2322

"react": "^16.12.0", "typescript": "^4.0.3", "next": "^9.4.4" The error being raised by typescript is related to the <Item item={item} key={item.id} urlReferer={urlReferer} /> prop used ...

Tips on using a dropdown menu to choose an item and automatically navigate to its specific details within an Angular framework

Here is the structure of my data : groups: [ { collections:[] }, { collections:[] }] I am utilizing nested *ngFor to showcase all groups and collections on a single page, which can make the list lengthy as more groups and collections are added. The hea ...

The property decorator in a TypeScript class behaves similarly to a static property

I have recently implemented a class using a property decorator that sets a flag within the class whenever a decorated property is updated. However, I am encountering an issue when trying to copy values from one instance of the class to another. It seems li ...