Search code examples
angulartypescriptprimengprimeng-dropdowns

PrimeNG dropdown selected option resets when bound with interface property


This is how I've declared the p-dropdown:

<p-dropdown name="taxOptions" [options]="taxOptions" [(ngModel)]="purchaseInvoiceDetail.tax"></p-dropdown>

The taxOptions property is populated like this:

this.taxOptions = [
      { label: 'Tax Exclusive', value: '0' },
      { label: 'Tax Inclusive', value: '1' }
];

This is the PurchaseInvoiceDetail interface:

export interface PurchaseInvoiceDetail {
  id: number,
  product: Product,
  quantity: number,
  unitPrice: number,
  discount: number,
  tax: string,
  purchaseInvoice: PurchaseInvoice
}

The table is populated using *ngFor on an array of PurchaseInvoiceDetail i.e. PurchaseInvoiceDetail[].

So a separate p-dropdown is present in each row of the table. The problem is that when I change the value of the dropdown and add another product the table refreshes and the selected option of the previous dropdown resets but not from the purchaseInvoiceDetail.tax. It only fails to fetch the value from purchaseInvoiceDetail.tax and show it as the selected value in the dropdown. Why is this happening?


Solution

  • dropdowns: Array<SelectItem[]>;
    
    
    <div *ngFor="let dropdown of dropdowns">
      <div *ngFor="let taxOption of dropdown">
         <p-dropdown name="taxOption" [options]="taxOption" 
         [(ngModel)]="purchaseInvoiceDetail.tax"></p-dropdown>
      </div>
    </div>
    

    SelectItem Interface

    export interface SelectItem {
      label: string;
      value: number;
    }
    

    this is the pattern you can follow, just adapt it to your rows.