app.component.html:
<div >
<label >Upload<span style="color:red">*</span></label>
<div >
<mat-form-field appearance="none">
<mat-chip-list #chipList aria-label="Fruit selection" >
<mat-chip *ngFor="let name of addedFiles" (removed)="remove(name)">
{{name}}
<!--<button matChipRemove>-->
<mat-icon matChipRemove >cancel</mat-icon>
<!--</button>-->
</mat-chip>
<!--<input [matChipInputFor]="chipList"-->
<!--[matChipInputSeparatorKeyCodes]="separatorKeysCodes"-->
<!--[matChipInputAddOnBlur]="addOnBlur"-->
<!--(matChipInputTokenEnd)="add($event)">-->
<input type="file" id="inputGroupFile" (change)="filesData($event , $event)" multiple style="display:none">
<label for="inputGroupFile">choose files</label>
</mat-chip-list>
</mat-form-field>
</div>
app.component.ts:
addedFiles = [];
filesData(files, event): void {
if (event.target.files.length > 5) {
this.alertService.error("Only 5 files are allowed");
event.preventDefault();
event.value = ""; // clear the older value
console.log(this.addedFiles);
} else if(event.target.files.length <=5){
for(let file of event.target.files){
this.addedFiles.push(file.name)
}
event.value ="";
}
}
In the above code i have added limit for uploading up to 5 files at a time. But if i add one by one file multiple times it is adding unlimited files. I need to upload only 5 files whether i had one by one or 5 by 5. Thanks.
CodePudding user response:
Just count length of addedFiles array. Like this:
addedFiles = [];
filesData(files, event): void {
if (this.addedFiles.length < 5) {
for(let file of event.target.files){
if(this.addedFiles.length < 5) {
this.addedFiles.push(file.name);
} else {
this.alertService.error("Only 5 files are allowed");
event.preventDefault();
event.value = ""; // clear the older value
break;
}
}
event.value ="";
} else {
this.alertService.error("Only 5 files are allowed");
event.preventDefault();
event.value = ""; // clear the older value
}
}