Search code examples
angularprimengp-dropdown

PrimeNG dropdown does not select value when loaded twice in component


I have a simple data model where a study has many samples. I set the p-dropdown's options, ngModel, and optionLabel during the ngOnInit method of the control:

<p-dropdown  [options]="samples" [(ngModel)]="selectedSample" optionLabel="name"></p-dropdown>

In the component's ngOnInit method, I listen for study changes and then populate the dropdown with the samples of that study. This works perfectly on the load of the page:

this.study$.subscribe((study)=>{
  this.selectedStudy = study;
  this.selectedSample = null;
  this.samples = study.samples;
  this.selectedSample = study.samples.filter(f => f.sampleId == study.selectedSample.sampleId)[0];      
  }
});  

When an event is raised from another control that would change the study, I have stepped through this code and see that the samples get correctly assigned and that the selectedSample is correctly assigned as well. But the p-dropdown is still showing the first value of the dropdown and not the actual selected value.

Why doesn't primeNg's dropdown work on the second time I set the values?


Solution

  • I found a solution only through gaining a reference to the Dropdown control via a ViewChild call from the component.

    @ViewChild('sampleDropdown') container?: Dropdown;
    
     <p-dropdown class="column-value"  
                  [options]="samples" [(ngModel)]="selectedSample" #sampleDropdown
                  (onChange)="onSampleChange($event)" 
                  optionLabel="name">
                </p-dropdown>
    

    When I would hit a breakpoint in the Observable that sets the values of the dropdown, I noticed that on the second time around, even after setting the samples property on the component, the actual control's options property was only reflecting the initial value from the first load. So I set the values manually using the following:

    if (this.container){
        this.container.options = this.samples;
    }
    

    The reason for the if test is that during ngOnInit, the control hasn't been created yet. But when the observable emits, the dropdown is there.

    Hopefully if anyone stumbles across PrimeNG's dropdown not selecting a value that is definitely present, this will help someone along.