Question:
P-Dropdown doesn't set Value manually with Reactive Form in Angular

Problem

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 a normal selector which work accordingly to what I expected. I did the same with the p-dropdown it 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 needs some reference on the <p-dropdown> in order to work?


Solution

There is a work around to solve this issue:


Add a template reference on the <p-dropdown> like #dd:


    <p-dropdown

      #dd

      formControlName="city"

      [options]="cities"

      optionLabel="name"

      (onChange)="onChange($event)"

    ></p-dropdown>


Use @ViewChild to read the template refenece:


  @ViewChild('dd') dd:Dropdown


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.


Suggested blogs:

>How to make the dropdown for this button ADA accessible in Angular?

>How to update properties value with event in template Angular?

>Unit Test Angular Standalone Component, Overriding Provider not used

>How to Import componet's own module using Angular?

>Why component does not display variable of another component in Angular?

>What are the ways to pass parameters to Angular service?

>How to access variables in a function using Angular?

>How can I close a bootstrap modal using Angular?

>Fix: Strange compilation error with Typescript and Angular

>Uploading files and JSON data in the same request with Angular

>CRUD Operations In ASP.NET Core Using Entity Framework Core Code First with Angularjs

>CRUD Operation on Angular

>What is pipe in Angular?

>A Complete Guide To Angular Routing


Nisha Patel

Nisha Patel

Submit
0 Answers