0

I have problem with cdkVirtualFor with FormArray. It doesn't generate any items.

My html:

<cdk-virtual-scroll-viewport
  [itemSize]="100"
  class="viewport-container"
  [formArrayName]="'items'"
>
  <div
    *cdkVirtualFor="
    let item of myFormArray.controls;
    let i = index;
    "
    [formGroupName]="i"
  >
    <div
    fxFlex
    fxLayout="row"
    fxLayoutAlign="start center"
    fxLayoutGap="17px"
    >
      <label>
        {{ i + 1 }}
      </label>
      <our-custom-form-field
        fxFlex
        [errorMessages]="validationErrors"
        [formControlName]="'option1'"
      >
        <input
         type="float"
        />
      </our-custom-form-field>
      <our-custom-form-field
        fxFlex
        [errorMessages]="validationErrors"
        [formControlName]="'option2'"
      >
        <input
          type="float"
         />
         </our-custom-form-field>
     </div>
  </div>
</cdk-virtual-scroll-viewport>

The myFormArray is getter

get myFormArray(): FormArray {
    return this.myFormBase?.get('items') as FormArray;
  }

And in this.myFormBase items are simply items: new FormArray([]) Before using cdk-virtual-scroll-viewport it was generated by ngFor, but due to occurrences of really large arrays I need to render some elements onScroll. But I don't know why this doesn't work. Controls exists, they are not nullish and all I see is blank space with size of .viewport-container class.

I tried generate those fields by using simple array with mock values like [1, 2, 3...] and it worked. Just don't know why it doesn't work with FormArray

EDIT: Problem was with myFormArray, when *cdkVirtualFor got it it was null, shortly after it was assigned with value, but cdk already rendered it with null. It worked properly when I passed the FormArray controls asynchronously.

Horsebye
  • 15
  • 4
  • I beg your pardon, but why do you need to inform the formArrayName? Just use this `itemSize="100" minBufferPx="900" maxBufferPx="1350"` is enought – rick Aug 01 '23 at 18:42
  • To ask for values and to set values. Without that I receives browser error - not found form control. That was the solution that I found to iterate thorugh FormArray in HTML and as I said with *ngFor it worked perfectly – Horsebye Aug 02 '23 at 06:03
  • instead of `FormArray` you can use `any[]` – rick Aug 02 '23 at 10:42
  • Solved problem, myFormArray was null when *cdkVirtualFor gets it, when I changed it to async it worked fine. But sadly more problems occured and due to lack of time we had to use *ngFor with limit to not generate enormous HTML on init. But appreciate your help – Horsebye Aug 03 '23 at 14:47
  • another thing, it is not recommended to use Getter for this kind of application. Use a property instead. Getter is slower than property. That's the reason it is null when reading by CdkvirtualFor – rick Aug 04 '23 at 10:50

0 Answers0