Home > Net >  How to fix angular error TS2322 (using an ngFor (FileList))
How to fix angular error TS2322 (using an ngFor (FileList))

Time:06-06

I fully understand that in angular we always need to pay attention to the type, but the error caused by this example is really incomprehensible.

I have a fileList, its type would be FileList, and when the user hasn't selected a file yet, the fileList certainly doesn't exist.

So in html I use ngIf to check if the fileList exists, and once it does, then ngFor loops it out.

HTML

<ng-container *ngIf="fileList">
  <mat-list-item *ngFor="let item of fileList">
    {{ item.name }}
  </mat-list-item>
</ng-container>

TS

fileList?: FileList;
---
onFileSelected(event: Event) {
  const targrt  = event.target as HTMLInputElement;
  const files   = targrt.files as FileList;
  if ( files ) {
    this.fileList = files;
  }
}

However, it responds to this message.

error TS2322: Type 'FileList' is not assignable to type 'any[] | Iterable | (Iterable & any[]) | (any[] & Iterable) | null | undefined'.

Please correct my mistake, how can I improve it? Thank any help.

CodePudding user response:

The error occurs at the line where you have mentioned:

const files   = targrt.files as FileList;

It happens because FileList is not an Array, and does not inherit from an Array, but it does implement the iterable protocol, so you can use the spread syntax to get it as an array OR you can convert it into an array type to use it for *ngFor purpose.

This method would help in this case. Array.from(target.files)

OR

[...target.files]

Improved code in your case:

fileList?: any[] = [];

onFileSelected(event: Event) {
  const targrt  = event.target as HTMLInputElement;
  fileList = Array.from(targrt.files);
  // OR, you can also do this
  // fileList = [...targrt.files];
}


<ng-container *ngIf="fileList && fileList.length > 0">
  <mat-list-item *ngFor="let item of fileList">
    {{ item.name }}
  </mat-list-item>
</ng-container>

I hope it helps..!!

CodePudding user response:

You can convert it to array and use it in *ngFor

const fileList = Array.from(yourFileList)
  • Related