如何编辑和更新动态添加的输入值 [英] How to edit and update the dynamically added input values
问题描述
场景:
下面是我的 json
文件,名为 contacts
:
我正在显示 contacts
(例如一个特定联系人)的 name
和 address
,如下所示:
预期结果:
- 我正在显示许多
addresses
,如果我点击特定的address
(对于 ex addressType:Home),我必须能够编辑该address
意味着我应该在下面的输入字段中获取地址值(即地址类型、城市、邮政编码),如下所示:
以便我可以编辑和更新该特定地址.
- 然后我应该可以从该输入字段中添加一个新的地址.
下面是我的stackblitz 演示
试试这个 在线示例
我改变了这些:
- 如果选择了地址,则使用更新模式,否则使用添加模式
- 将表单数据添加到特定索引的联系人数组
- 更新从您的编辑数据中选择的地址
selectAddr(addr) {this.newAttribute.addressType = addr.addressType;this.newAttribute.postalCode = addr.postalCode;this.newAttribute.city = addr.city;this.selectedAddr = addr;}保存地址(索引,表单:FormGroup){常量模式:'更新' |'添加' = this.selectedAddr ?'更新':'添加';如果(模式 === '添加'){this.contacts[index].addresses.push({ ...this.newAttribute });} else if (mode === '更新') {Object.assign(this.selectedAddr, this.newAttribute);}//重启this.selectedAddr = 未定义;表单.重置();}
<form [formGroup]="addForm" #myForm><p>姓名:{{contact.name}}</p><br><!--地址部分--><div class="address-sec"><p id="addr">地址</p><br><table style="width:100%" *ngFor="let addr of contact.addresses"><tr><td><div id="字段类型"><mat-chip-list><mat-chip color="primary" (click)="selectAddr(addr)" selected>{{addr.addressType}}</mat-chip></mat-chip-list></td><td><div class="field-data">{{addr.city}}-{{addr.postalCode}}
</td><td><div class="field-data"><b>删除</b>
</td></tr><小时><br>
<br><!--地址部分--><mat-form-field><mat-select formControlName="addressType" placeholder="Type" [(ngModel)]="newAttribute.addressType"><mat-option *ngFor="let addressType of addresstypes" [value]="addressType.value">{{addressType.viewValue}}</mat-option></mat-select></mat-form-field><br><mat-form-field ><input matInput formControlName="postalCode" [(ngModel)]="newAttribute.postalCode" placeholder="邮政编码" ></mat-form-field><br><mat-form-field ><input matInput formControlName="city" [(ngModel)]="newAttribute.city" placeholder="City" ></mat-form-field><br><br><br><br><br><button mat-flat-button (click)="saveAddress(i,myForm)">保存</button></表单><br><小时>