Reputation: 197
I defined, initialized(TWICE) my array, yet i am getting "ERROR TypeError: Cannot read property 'length' of undefined" at runtime.
I already tried to check if the array was defined as you can see in my code, still angular is just trolling me. I already tried all solutions like changing the sintax to "filesToUpload && filesToUpload?.length > 0" or any possible combination, however Angular is just not working properly imo.
component.html file
<ng-container *ngIf="undefined !== filesToUpload && filesToUpload.length > 0">
<button (click)='uploadImages()'
class="btn btn-success"
type="button">
<i class="fas fa-upload"></i>Upload
</button>
<button (click)='cancelUpdate()'
class="btn btn-danger"
type="button">Cancel</button>
</ng-container>
This is my component.ts file
export class ImageGalleryUploadComponent implements OnInit
{
filesToUpload: File[] = [];
ngOnInit() {
this.filesToUpload = []
}
}
is this an angular bug? or has something to do with component lifecycle?
Upvotes: 0
Views: 3467
Reputation: 6016
Try this, somewhere you are assigning undefined
to your Array object.
<ng-container *ngIf="filesToUpload && filesToUpload != 'undefined' && filesToUpload.length > 0">
Though it's not a good practice, just try it once and if confirmed then cross-check in your code.
Upvotes: 2
Reputation: 956
Just do it once like:
export class ImageGalleryUploadComponent implements OnInit
{
filesToUpload: File[] = [];
}
I have faced this issue as well. Removing the re-initialisation from ngOnInit
should fix the issue. And don't worry every time the component is initialised it will be set to []
.
Upvotes: 0
Reputation: 222722
Try this way using safe navigation operator and it will handle null and lentgh of files in one go,
<ng-container *ngIf="filesToUpload && filesToUpload?.length > 0">
Upvotes: 2