【发布时间】:2018-07-17 17:17:09
【问题描述】:
我无法将正确的值填充到 FormArray 的输入字段中。这是我的html:
<div formArrayName="roles" *ngFor="let role of roles.controls; let i=index">
<div [formGroupName]="i">
<div class="form-group row">
<label class="col-md-2 col-form-label" attr.for="{{'roleNameId' + i}}">Role Name {{i+1}}</label>
<div class="col-md-6">
<input class="form-control"
attr.id="{{'roleNameId' + i}}"
type="text"
formControlName="roleName">
</div>
<label class="col-md-2 col-form-label" attr.for="{{'identifierId' + i}}">
<input
type="checkbox"
attr.id="{{'identifierId' + i}}"
formControlName="identifier"> identifier
</label>
<div class="col-md-2">
<button type="button" (click)="removeRole(i)" class="btn btn-danger oi oi-trash"></button>
</div>
</div>
</div>
</div>
所以这个 html 被渲染 x 次,具体取决于我拥有的角色数量。这工作得很好,没有显示错误。
但问题是:当我删除一个不是数组的最后一个角色时,填充正确角色的输入字段会发生变化。 以下是角色:
role2 被正确删除,但 role3 消失了,最后两个角色具有最后一个角色 (role8) 的名称
为什么会这样?当我查看保存所有角色的 formArray 时,该数组具有正确的值,这是证据:
为什么视图中没有显示正确的值?谢谢你的帮助
编辑:这是相关的打字稿代码:
this.sourcesForm = this.fb.group({
sourceName: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(255)]],
sourceType: ['QUERY'],
dsl: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(255)]],
list: [''],
roles: this.fb.array([this.buildRole()]),
database: [''],
});
// save roles to temporary variable to map for the roles Formarray
let roles = [];
dslStatement.roles.forEach(role => {
let oneRole = {
roleName: role.name,
identifier: true
}
if (role.role === 'IDENTIFIER')
oneRole.identifier = true;
else
oneRole.identifier = false
roles.push(oneRole);
});
// convert the variable to FormGroups, then the FormGroups to one FormArray
// and at last set the FormArray to the roles of sourcesForm
const rolesFormGroups = roles.map(roles => this.fb.group(roles));
const rolesFormArray = this.fb.array(rolesFormGroups);
this.sourcesForm.setControl('roles', rolesFormArray);
buildRole(): FormGroup {
return this.fb.group({
roleName: '',
identifier: true
});
}
addRole() {
this.roles.push(this.buildRole());
}
removeRole(i: number) {
this.roles.removeAt(i);
console.log(this.roles.value);
console.log(this.roles.controls);
}
【问题讨论】:
-
你能举个例子吗?
-
html 在这里无关紧要。看起来像数据封装的一些问题。展示你得到了什么
-
显示
removeRole的代码 -
我通过添加相关代码sn-ps更新了问题
-
在
removeRole中尝试(<FormArray>this.sourcesForm.get('roles')).removeAt(i)而不是this.roles.removeAt(i)
标签: html angular angular-reactive-forms angular-forms formarray