Angular实现表格列控件值同步并点击按钮保存SchemeDB对象
实现方案
模板绑定调整
移除原有复选框上多余的点击alert逻辑,给控件加上与字段对应的双向绑定,修改会直接实时同步到原对象:
<div class="card" *ngFor="let table of schema.tables | keyvalue"> <!-- 卡片头部、折叠交互、样式类保持原有代码完全不变 --> <div class="card-header border-top headerCollapse p-0" [attr.id]="'heading' + table.key"> <h5 class="mb-0"> <button class="collapsed AccodeonTitle activeAccodeonTitle" data-toggle="collapse" [attr.data-target]="'#collapse' + table.key" aria-expanded="false" [attr.aria-controls]="'#collapse' + table.key"> <span>{{table.value.name}}</span> </button> </h5> <svg data-toggle="collapse" [attr.data-target]="'#collapse' + table.key" width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-chevron-up collapseIcon collapseIconActive" fill="currentColor" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" d="M7.646 4.646a.5.5 0 0 1 .708 0l6 6a.5.5 0 0 1-.708.708L8 5.707l-5.646 5.647a.5.5 0 0 1-.708-.708l6-6z"/> </svg> </div> <div [attr.id]="'collapse' + table.key" class="collapse show" aria-labelledby="headingOne" data-parent="#accordion"> <div class="card-body p-0"> <table class="ConfigurationTable selectTable pl-5"> <thead class="theadSelectTable"> <tr> <th> <div class="d-flex align-items-center"> <span class="colLogo"></span> <span class="d-inline-block pl-3">Columnas</span> </div> </th> <th></th> </tr> </thead> <tbody> <tr *ngFor="let column of table.value.columns | keyvalue"> <td> <!-- 复选框直接绑定到Column接口的checked字段 --> <input type="checkbox" aria-label="Checkbox for following text input" [(ngModel)]="column.value.checked" > <span class="pl-3">{{column.value.name}}</span> </td> <td class="selectProperties"> <!-- 下拉框直接绑定到Column接口的typeEnt字段 --> <select class="custom-select customPlaceHolder tablePlaceHolder custom-select-table" [(ngModel)]="column.value.typeEnt" > <option [ngValue]="'Base de datos_06'">Base de datos_06</option> <option [ngValue]="'PER'">PER</option> <option [ngValue]="'NUM'">NUM</option> <option [ngValue]="'DATA'">DATA</option> </select> </td> </tr> </tbody> </table> </div> </div> </div>
模块依赖准备
要使用Angular的双向绑定能力,需先在对应业务模块引入FormsModule,否则模板中的[(ngModel)]会失效:
import { FormsModule } from '@angular/forms'; @NgModule({ imports: [ // 其他原有业务模块 FormsModule ] }) export class YourBusinessModule {}
保存逻辑实现
因为绑定过程直接引用原SchemeDB对象内的字段,没有做值拷贝,所以保存按钮触发时,直接读取当前组件内的schema变量就是修改完成后的完整对象,不需要额外遍历收集数据:
// 保存按钮触发的方法 onSaveConfig() { // 传入的schema已包含所有复选框选中状态、下拉框的修改值 this.apiService.saveUpdatedSchema(this.schema).subscribe(res => { // 保存成功后的业务逻辑 }) }
注意事项
- 不要在模板渲染时对表、列对象做深拷贝,否则会断开和原对象的引用关联,修改值无法回写
- 下拉选项统一用
[ngValue]绑定实际存储值,不要硬编码selected属性,否则初始选中值会和对象状态不匹配 - 如果后续要扩展其他可编辑字段,直接在对应控件上加同样的双向绑定即可,不需要手动写事件监听同步值
内容的提问来源于stack exchange,提问作者María
相关产品推荐
相关产品推荐

