angular - 角度反应形式,仅编辑列表中的选定行
问题描述
我正在尝试使用数组构建动态 Angular Reactive Form。我想要的是显示一个包含静态数据(不可编辑)的表格,并在每一行上都有一个编辑/删除图标。当用户单击编辑按钮时,选定的行数据将显示在表格下方的 dit 形式中。
表格有一些一般数据(例如,一个人有名字和姓氏以及地址列表)
模板:
<form [formGroup]="placesForm" class="card mx-4" (submit)="onSubmit()">
Firstname <input class="form-control" formControlName="firstName" />
Lastname <input class="form-control" formControlName="lastName" />
Your addresses :
<table class="table table-striped" >
<tr *ngFor="let place of placesForm.get('places').controls; let i=index">
<td>{{i}}</td>
<td>{{place.get('street').value}}</td>
<td>{{place.get('city').value}}</td>
<td>{{place.get('zipCode').value}}</td>
<td width="35"><i class="icon-pencil" (click)="editPlace(i)" title="Edit"></i> <i class="icon-trash" (click)="removePlace(i)" title="Delete"></i> </td>
</tr>
</table>
<div *ngIf="selectedPlace">
<app-address-form [addressForm]="placesForm.get('places').at(selectedPlace)"></app-address-form>
</div>
</form>
组件:
export class Step2PlacesComponent implements OnInit {
private placesForm: FormGroup;
private selectedPlace = 0;
constructor(
private fb: FormBuilder,
) {
}
ngOnInit() {
this.placesForm = this.fb.group({
firstName: [null],
lastName: [null],
places: this.fb.array([this.fb.group({
street: [null, Validators.required],
city: [null, Validators.required],
zipCode: [null, Validators.pattern(/\d+/)]
})])
});
}
onSubmit() {
}
addPlace() {
places.push(this.fb.group({
street: [null, Validators.required],
city: [null, Validators.required],
zipCode: [null, Validators.pattern(/\d+/)]
}));
}
editPlace(index) {
this.selectedPlace = index;
}
removePlace(index) {
let places = (<FormArray>this.placesForm.get('places'));
places.removeAt(index);
if (this.selectedPlace >= places.controls.length) {
this.selectedPlace --;
}
}
}
app-address-form
模板:
<div [formGroup]="addressForm">
<input class="form-control" formControlName="street" />
<input class="form-control" formControlName="city" />
<input class="form-control" formControlName="zipCode" />
</div>
和app-address-form
组件:
export class AddressFormComponent implements OnInit {
@Input() addressForm: FormGroup;
constructor() {
}
ngOnInit() {
}
}
当我单击编辑按钮时, selectedPlace 会相应更新,但 app-address-form 组件未更新,我仍在编辑第一行。
也许placesForm.get('places').at(selectedPlace)
不是正确的做法,但我不知道该怎么做。
解决方案
推荐阅读
- azure - 在 Azure 中监控特定的 IoT 设备?
- javascript - 从拦截器Angular调用异步函数到catch
- html - 用于快速格式化 HTML 上的选择的 VS Code 键绑定
- r - 在R中使用因子时如何调整网格大小以删除没有数据的区域?
- dataframe - 确定 pyspark DataFrame 行值是否存在于其他列中
- javascript - 如何在原始数据中搜索匹配数据?
- c# - 使用 ASP.NET MVC 成功登录 AngularJS 后导航到所需页面
- apache - Ubuntu Server 16.04 错误 60:SSL 证书问题
- google-apps-script - 响应式 ModalDialog/ModelessDialog 谷歌脚本
- java - 模糊联系服务的 Java JUnit 问题