Angular *ngFor循环场景下如何正确传值给模态框实现文件预览
问题根源拆解
两个异常本质都是Angular模板的作用域绑定错位导致的,没有复杂的底层bug:
- 你在模态框里绑定的
file.name、图片拼接路径用到的file,是*ngFor循环里的局部作用域变量。一旦把模态框移到表格外部,这个位置已经脱离了*ngFor的作用域,根本取不到循环内的局部变量值,自然出现内容空、显示失效的问题。 - 把模态框塞在
<td>标签内部时,Angular会为每个循环条目生成一份独立的模态框副本。但所有副本的显示状态,绑定的都是组件级的同一个showModal变量。只要点击任意按钮把showModal设为true,所有循环生成的模态框都会触发显示,DOM最终渲染在最顶层的永远是列表最后一个条目对应的模态框,就会出现“不管点哪个按钮,都只显示最后一张预览图”的问题。 - 模态框移到表格外就“不生效”还有一个附加原因:自带的
.modal类默认z-index层级较低,移到表格外部后容易被其他DOM元素遮挡,视觉上看起来就是显示异常。
完整修复实现
第一步:改造组件类的逻辑
新增专门存储当前选中预览文件的组件属性,改造触发方法,把当前点击的文件对象传入并存下来:
// 组件类属性 showModal = false; // 存储当前要预览的文件对象,替代直接引用循环作用域的file currentPreviewFile: any = null; // 改造后的模态框触发方法,接收当前点击的文件参数 show(currentFile: any) { this.currentPreviewFile = currentFile; this.showModal = true; } // 保留原有关闭方法,增加清空选中值的逻辑 hide() { this.showModal = false; this.currentPreviewFile = null; }
第二步:改造表格内的按钮触发逻辑
把原来无参的show()方法调用,改成把当前循环的file对象当参数传入:
<tr *ngFor="let file of fileUploads | async | filter: name | paginate: { itemsPerPage: 10, currentPage: p }; let i = index"> <td id="lPart" style="cursor: pointer; font-weight: normal;"> <a href="http://localhost:3000/files/{{file.name}}{{file.ext}}">{{file.name}}</a> <button type="button" class="btn btn-sm btn-default" (click)="show(file)" > 预览 </button> </td> </tr>
原来按钮上重复显示文件名的逻辑可以根据自己的需求调整,核心是把当前file传给方法。
第三步:把模态框移到表格外部,绑定全局存储的预览文件
把模态框放在组件根节点下(也就是整个表格结束之后的位置),不再嵌套在<table>/<tr>/<td>内部,同时把原来模态框里绑定的循环作用域file,全部替换成组件级存储的currentPreviewFile:
<!-- 表格结束之后,组件最外层位置放模态框 --> <div *ngIf="showModal" class="modal" id="imagemodal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: block; z-index: 1050;" > <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="myModalLabel"> {{currentPreviewFile?.name}} </h4> </div> <div class="modal-body"> <img [src]="'http://localhost:3000/files/' + currentPreviewFile?.name + currentPreviewFile?.ext" id="imagepreview" style="width: 425px; height: 425px;" > </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal" (click)="hide()" > Close </button> </div> </div> </div> </div>
这里做了三个细节优化,从根源避免之前的显示异常:
- 用
*ngIf="showModal"替代原来的[style.display]控制显示,比手动控制样式更干净,不会残留空白DOM - 图片路径用Angular的属性绑定
[src]写,配合可选链?.,就算currentPreviewFile还没赋值,也不会出现模板路径拼接报错的问题 - 给模态框加了足够高的
z-index,避免移到表格外部后,被其他DOM元素压在下面看起来“不生效”
内容的提问来源于stack exchange,提问作者MarkeZ
相关产品推荐
相关产品推荐

