Angular 11循环调用组件时如何获取触发附件上传的对应组件索引
问题根源
你所有chat-window组件里的文件选择<input>都用了固定的id="file",对应的<label>也用了固定的for="file"。HTML规范中id是全局唯一的,所以不管你点击哪个聊天窗口的附件按钮,系统都会默认触发页面里第一个id="file"的输入框,也就是索引为0的聊天窗口的上传逻辑,所以才会一直拿到索引0。
解决方法
修改chat-window.html中文件上传相关的代码,将固定id改为和当前组件索引绑定的动态id,保证每个组件的id唯一:
<div class="file"> <input type="file" multiple (change)="attchment($event)" name="file" id="file-{{index}}" /> <label for="file-{{index}}" title="select files"> <span><i class="fas fa-paperclip"></i></span> <span *ngIf="chat.files.length > 0"> {{ chat.files.length }} </span> </label> </div>
修改后每个label只会触发当前组件对应的文件输入框,就能正确拿到对应聊天窗口的索引了。
可选优化
你可以调整chat-window.ts的附件触发逻辑,直接把处理好的文件数组传给父组件,不需要父组件再从原始事件里解析文件:
// chat-window.ts attchment(event) { this.files = []; for (let i = 0; i < event.target.files.length; i++) { this.files.push(event.target.files[i]); } this.onAttachment.emit({ files: this.files, index: this.index }); } // 父组件 live session.ts newAttachment(event) { this.slots[event.index].files = event.files; console.log(this.slots[event.index]); }
内容的提问来源于stack exchange,提问作者Mohd Sabban
相关产品推荐
相关产品推荐

