Search code examples
angularprimeng

PrimeNG dropdown isn't updating UI when using patchValue()


I am using a reactive form with a couple of fields. Three dropdowns and one calendar, all of them are PrimeNG components. All fields, except the project field, update their values in the UI after calling patchValue().

I have logged the value going into the form in patchValue() and also logged the form afterwards. The form shows the correct value, but the UI isn't updated and just selects the first value. The project array is filled long before patchValue() is called.

I have the feeling that it has something to with the project's ID being a GUID. The other dropdowns bind to an enum value.

I have tried a couple of things:

  • Add placeholder to dropdown (a post suggested this)
  • Using the project object as value instead of only the id field
  • Formatting the GUID without dashes and use that as value
  • Set a timeout around patchValue()
  • Move patchValue() to ngAfterViewInit()

All these things did not solve the issue. I can't seem to find anyone else with this issue, is it because I am using a weird datatype for the value? I never faced any issues with strings being used as values before. Anyways, here is the code.

Constructor

this.calculationForm = new UntypedFormGroup({
  'project': new UntypedFormControl(null),
  'status': new UntypedFormControl(0),
  'type': new UntypedFormControl(0),
  'deadline': new UntypedFormControl(new Date(), [Validators.required])
}); 

ngOnInit

this.calculationForm.patchValue({
  'project': this.calculation.project.id,
  'status': this.calculation.status,
  'type': this.calculation.type,
  'deadline': new Date(this.calculation.deadline)
});

Project interface

export interface Project {
  id: string;
  code: string;
  description: string;
}

HTML

<div class="field">
  <label for="project">{{ 'calculations.edit.project.label' | translate }}</label>
  <p-dropdown
    id="project"
    inputId="project"
    [options]="projects"
    formControlName="project"
    optionValue="id"
    optionLabel="code"
    appendTo="body"
  ></p-dropdown>
</div>
  • Angular ^14.1.0
  • PrimeNG ^14.0.0

Thank you in advance.


Solution

  • In the end, the issue was related to the dropdown's key field being case sensitive. The project GUID was being returned lowercase from the backend while the projects array had uppercase GUIDs.