Search code examples
angularangular-reactive-formsprimengprimeng-dropdowns

p-dropdown doesn't setValue manually with Reactive Form


I'm trying to set manually the form after some services retrieve some information, and I need to set back again to the dropdown the values (using setTimeout for practicity).

Along side are a normal selector which work accordingly to what I expected. I did the same with the p-dropdown i doesn't work at all.

It detected the change by the method onChange but again nothing happen.

https://stackblitz.com/edit/ge9bjb?file=src%2Fapp%2Fdemo%2Fdropdown-reactive-forms-demo.ts

Maybe it need some reference on the <p-dropdown> in order to work?


Solution

  • There is a work around to solve this issue:

    1. Add a template reference on the <p-dropdown> like #dd:
        <p-dropdown
          #dd
          formControlName="city"
          [options]="cities"
          optionLabel="name"
          (onChange)="onChange($event)"
        ></p-dropdown>
    
    1. Use @ViewChild to read the template refenece:
      @ViewChild('dd') dd:Dropdown
    
    
    1. Add the following in SetTimeout to update the model value:
        setTimeout(() => {
          this.cityName?.patchValue(this.cities[1], { onlySelf: true });
          this.dd.updateModel(this.cities[1]) // add this line to update model
          console.log(this.formGroup.getRawValue().city);
          console.log(this.formGroup2.getRawValue().cityName);
        }, 2000);
    

    That should works fine with you.

    I think that happened because of modelValue signal in dropdown component under the hood.