Home > other >  Primeng how to make sure dropdown formControlName is assigned after options was loaded
Primeng how to make sure dropdown formControlName is assigned after options was loaded

Time:09-05

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"
      
      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.

CodePudding user response:

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 ;)

  • Related