0

I have primeng dropdown p-drowdown and fetching options value from database. But the problem is dropdown value formControlName="fromWarehouseId" is assigned before [options]="fromWarehouseList" is assigned. For example ;

 <p-dropdown
     #fromWareHouse
      [options]="fromWarehouseList"
      class="w-100"
      formControlName="fromWarehouseId"
      placeholder="{{ 'form.btn.select' | translate }}"
    >
 </p-dropdown>

I have this dropdown in my component template. When the page is loaded fromWarehouseList is being assigned asynchronously but the formControlName fromWarehouseId is being assigned immediately and as a result user can't see dropdown value correctly. What I have tried so far ;

  1. Tried to use observable to notify parent component when p-dropdown is rendered. But couldn't manage

  2. Tried to use ngAfterViewInit in parent component but didn't change anything.

  3. Tried to use settimeOut but ı don't think it's right thing to do.

  • After the values have been set, use `setValue` to set the formcontrol value. – AT82 Sep 04 '22 at 14:38
  • You can also display the dropdown conditionally, so you can make sure it is only rendered when all the data needed to do so is available. – Allan Juan Sep 04 '22 at 14:46
  • I already tried but it's not working. Because I fetching values and options from database seperately. Even if I use `setValue` after options has been set, I can't guarantee value has been fetched from database. – seniorlearner Sep 04 '22 at 14:51
  • I tried it. But this time it's making other parts broken. For example for this I added `*ngIf="fromWarehouseList.lengtn>0` but I'm using same form to display and create data. So when user tries to create a data using this form, it's not being rendered .Becasuse list is empty when user tries to create a form @Allan Juan – seniorlearner Sep 04 '22 at 14:54
  • If it depends on 2 values being fetched, use `forkJoin` to run the both async request at same time. – AT82 Sep 04 '22 at 14:57

1 Answers1

0

Since you in comment say that both values, fromWarehouseList and the formcontrol value is being fetched async, then use forkJoin (using observables) to run the request at the same time, so you then also know when you have both values. So, something like this:

forkJoin([this.getDataForTable(), this.getValueForFormControl()])
 .subscribe([tableData, formControlData] => {
   this.fromWarehouseList = tableData;
   this.myForm.get('fromWarehouseId').setValue(formControlData);
 })

Of course, type your data, here I have not, as I don't know how your data looks like, or what your types are ;)

AT82
  • 71,416
  • 24
  • 140
  • 167