Angular表格行编辑功能异常:点击更新新增行而非修改原有数据
问题原因
你代码的核心问题出在update方法的逻辑错误:
- 编辑时你在
edit方法中存储的itemobj是行数据的原始旧对象,调用更新逻辑时你直接把这个旧对象赋值给了数组对应下标,完全没有读取用户在模态框中修改后的表单最新值,所以修改的内容不会生效。 - 额外隐患:新增表单和编辑模态框共用了同一个
userform实例,编辑后如果不重置表单,下次新增数据时会自动带上之前编辑的内容。
修正后的TypeScript代码
import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { Router } from '@angular/router'; declare var bootstrap: any; // 使用原生Bootstrap的话需要加这行声明 @Component({ selector: 'app-contact', templateUrl: './contact.component.html', styleUrls: ['./contact.component.scss'], }) export class ContactComponent implements OnInit { userform: FormGroup; listdata: any[] = []; editIndex: number = -1; // 用数字类型存储编辑下标,比any类型更安全 constructor(private route: Router, private formbuilder: FormBuilder) { this.userform = this.formbuilder.group({ name: ['', Validators.required], Phone: ['', Validators.required], }); } submit(): void { this.listdata.push(this.userform.value); this.userform.reset(); } update(): void { if (this.editIndex < 0 || this.editIndex >= this.listdata.length) return; // 读取表单最新修改值,更新到对应下标位置 this.listdata[this.editIndex] = {...this.userform.value}; this.userform.reset(); this.editIndex = -1; // 关闭编辑模态框 const modalEle = document.getElementById('exampleModal'); if (modalEle) { bootstrap.Modal.getInstance(modalEle)?.hide(); } } edit(item: any): void { // 表单回填原始数据 this.userform.patchValue({ name: item.name, Phone: item.Phone, }); // 存储当前编辑行的下标 this.editIndex = this.listdata.indexOf(item); } removeitem(element: any) { const index = this.listdata.indexOf(element); if (index > -1) { this.listdata.splice(index, 1); } } ngOnInit(): void {} }
可选优化
模板中存在两处拼写错误,不影响功能但建议修正:
form-contorl改为form-controlplacdeholder改为placeholder
内容的提问来源于stack exchange,提问作者bhargav kumar
相关产品推荐
相关产品推荐

