Angular中点击编辑按钮实现指定索引数据编辑与保存问题求助
解决方案
问题根源是你用了单个布尔值editing控制所有列表项的编辑状态,点击编辑按钮时该变量变为true,导致所有项同步触发编辑状态。需要改成记录当前编辑项的索引,实现单条数据的精准编辑。
步骤1:修改组件TS文件
替换全局布尔变量为索引变量,用来存储当前正在编辑的项的索引(无编辑状态时设为null):
// 替换原来的editing: boolean = false; editingIndex: number | null = null; editClick = (command: string, index: number) => { this.logger.trace('editClick() called with command', command); // 直接使用ngFor传过来的索引,无需重复查找 this.editingIndex = index; this.logger.trace('当前编辑项索引:', index); }; // 可选:添加取消编辑的方法(比如点击保存或输入框失焦时调用) cancelEdit() { this.editingIndex = null; }
步骤2:修改HTML模板
将所有依赖editing的判断逻辑,替换为基于editingIndex与当前项索引的对比:
<div id="vtu-command-div"> <ul id="selected-command-list" class="list-group"> <li class="list-group-item" *ngFor="let command of selectedVtuCommands; let commandIndex = index" > <!-- 非编辑状态显示文本 --> <div class="mt-2 d-inline-block" *ngIf="editingIndex !== commandIndex"> {{ command }} </div> <!-- 编辑状态显示输入框 --> <div id="inputediv" *ngIf="editingIndex === commandIndex"> <input class="mt-2 d-inline-block" type="text" [(ngModel)]="selectedVtuCommands[commandIndex]" (blur)="cancelEdit()" <!-- 可选:失焦自动取消编辑 --> /> </div> <button (click)="deleteVtuCommand(command)" class="btn btn-danger pull-right ml-2" > <i class="fa fa-trash"></i> </button> <!-- 仅非编辑项显示编辑按钮 --> <button *ngIf="editingIndex !== commandIndex" class="btn btn-danger pull-right" (click)="editClick(command, commandIndex)" > <i class="fa fa-pencil" aria-hidden="true"></i> </button> <!-- 可选:编辑状态显示保存按钮 --> <button *ngIf="editingIndex === commandIndex" class="btn btn-success pull-right" (click)="cancelEdit()" > <i class="fa fa-check" aria-hidden="true"></i> </button> </li> </ul> </div>
额外说明
- 原代码中
[(ngModel)]="command"绑定存在问题:command是*ngFor循环的临时变量,直接绑定无法更新原数组selectedVtuCommands,改为[(ngModel)]="selectedVtuCommands[commandIndex]"才能正确修改数组元素。 - 你之前在
editClick里用findIndex重复获取索引是多余的,*ngFor已经通过commandIndex传递了当前项的索引,直接使用即可。
内容的提问来源于stack exchange,提问作者Muhammadsaied
相关产品推荐
相关产品推荐

