如何禁用ng-zorro nz-upload上传中的文件移除选项?
嗨,我之前在项目里用ng-zorro的nz-upload组件时也碰到过一模一样的问题!给你几个实用的解决方案,应该能帮你搞定:
方案一:上传期间直接隐藏/禁用移除按钮
最直接的方式就是在文件上传过程中,不让用户看到或者点击移除按钮。你可以通过自定义nzItemRender模板来实现,根据文件的status字段判断当前是否处于上传状态:
<nz-upload [nzFileList]="fileList" [nzItemRender]="customUploadItem" [nzAction]="'/your-upload-api'" [nzAccept]="'.pdf'" > <button nz-button><i nz-icon nzType="upload"></i> 选择PDF文件</button> </nz-upload> <!-- 自定义上传项模板 --> <ng-template #customUploadItem let-file> <div class="ant-upload-list-item"> <div class="ant-upload-list-item-info"> <span class="ant-upload-list-item-name">{{ file.name }}</span> <!-- 上传中显示进度条 --> <nz-progress *ngIf="file.status === 'uploading'" [nzPercent]="file.percent" nzSize="small" ></nz-progress> </div> <div class="ant-upload-list-item-actions"> <!-- 只有非上传状态才显示移除按钮 --> <button nz-button nzSize="small" nzType="text" *ngIf="file.status !== 'uploading'" (click)="handleFileRemove(file)" > <i nz-icon nzType="delete"></i> </button> </div> </div> </ng-template>
对应的组件逻辑里,处理移除的函数可以正常写:
import { NzUploadFile } from 'ng-zorro-antd/upload'; import { NzMessageService } from 'ng-zorro-antd/message'; constructor(private msg: NzMessageService) {} fileList: NzUploadFile[] = []; resultArray: any[] = []; // 存储上传响应结果的数组 handleFileRemove(file: NzUploadFile): void { this.fileList = this.fileList.filter(item => item.uid !== file.uid); // 同时从结果数组移除对应项(如果有的话) this.resultArray = this.resultArray.filter(item => item.uid === file.uid); this.msg.success('文件已移除'); }
方案二:拦截移除操作,上传中阻止用户移除
如果不想隐藏按钮,而是希望用户点击移除时给出提示并阻止操作,可以利用nzRemove事件来拦截:
<nz-upload [nzFileList]="fileList" [nzAction]="'/your-upload-api'" [nzAccept]="'.pdf'" (nzRemove)="handleRemoveIntercept($event, file)" > <button nz-button><i nz-icon nzType="upload"></i> 选择PDF文件</button> </nz-upload>
组件逻辑里判断文件状态:
handleRemoveIntercept(e: Event, file: NzUploadFile): boolean { if (file.status === 'uploading') { this.msg.error('文件正在上传中,无法移除,请稍候'); // 返回false阻止默认的移除行为 return false; } // 正常移除逻辑 this.fileList = this.fileList.filter(item => item.uid !== file.uid); this.resultArray = this.resultArray.filter(item => item.uid === file.uid); return true; }
方案三:优化结果数组逻辑,避免异常
如果允许用户移除上传中的文件,那就要处理上传请求取消和数组同步的问题。ng-zorro的每个上传文件对象里会包含xhr属性,我们可以用它来取消上传请求,同时更新结果数组:
handleRemoveIntercept(e: Event, file: NzUploadFile): boolean { if (file.status === 'uploading') { // 取消当前上传请求 if (file.xhr) { file.xhr.abort(); } this.msg.info('已取消文件上传'); } // 同步更新文件列表和结果数组 this.fileList = this.fileList.filter(item => item.uid !== file.uid); this.resultArray = this.resultArray.filter(item => item.uid !== file.uid); return true; }
另外,建议你在处理上传成功的nzSuccess事件时,先检查文件是否还在文件列表中(避免用户已经移除但请求还在进行的情况),再将结果加入数组:
handleUploadSuccess(res: any, file: NzUploadFile): void { // 检查文件是否还存在于文件列表中 const isFileExist = this.fileList.some(item => item.uid === file.uid); if (isFileExist) { this.resultArray.push({ ...res, uid: file.uid }); this.msg.success('文件上传成功'); } }
这几个方案都能解决你遇到的数组异常问题,你可以根据自己的业务需求选择最合适的~
内容的提问来源于stack exchange,提问作者Michael




