【发布时间】:2018-06-03 10:37:23
【问题描述】:
前言:
我很难弄清楚嵌套角度形式听起来像是一个简单的过程。我在这里处理一些组件,其中一些 formGroups 和 formArrays 是动态创建的,它让我失望。
为大量代码转储道歉,但这是我能够想出的最小示例来尝试解释我的问题。
父组件非常简单,因为它只有两个formControls。然后我将表单传递给tasks 组件以访问它。
父组件
this.intakeForm = this.fb.group({
requestor: ['', Validators.required],
requestJustification: ['', Validators.required]
});
HTML:
<form [formGroup]=“intakeForm”>
<app-tasks
[uiOptions]="uiOptions"
[intakeForm]="intakeForm">
</app-tasks>
</form>
任务组件
这里的某些方法会触发generateTask,它会创建新的表单组。
ngOnInit() {
this.intakeForm.addControl('tasks', new FormArray([]));
}
// Push a new form group to our tasks array
generateTask(user, tool) {
const control = <FormArray>this.intakeForm.controls['tasks'];
control.push(this.newTaskControl(user, tool))
}
// Return a form group
newTaskControl(user, tool) {
return this.fb.group({
User: user,
Tool: tool,
Roles: this.fb.array([])
})
}
HTML:
<table class="table table-condensed smallText" *ngIf="intakeForm.controls['tasks'].length">
<thead>
<tr>
<th>Role(s)</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let t of intakeForm.get('tasks').controls let i = index; trackBy:trackByIndex" [taskTR]="t" [ui]="uiOptions" [intakeForm]="intakeForm" [taskIndex]="i">
</tr>
</tbody>
</table>
TR 组件
这里的某些方法将触发addRole 方法,该方法将添加表单组。
@Input('taskTR') row;
@Input('ui') ui;
@Input('intakeForm') intakeForm: FormGroup;
// Add a new role
addRole($event, task) {
let t = task.get('Roles').controls as FormArray;
t.push(this.newRoleControl($event))
}
// Return a form group
newRoleControl(role) {
return this.fb.group({
Role: [role, Validators.required],
Action: [null, Validators.required]
})
}
HTML
<td class="col-md-9">
<ng-select [items]="ui.adminRoles.options"
bindLabel="RoleName"
bindValue="Role"
placeholder="Select one or more roles"
[multiple]="true"
[clearable]="false"
(add)="addRole($event, row)"
(remove)="removeRole($event, row)">
</td>
问题
我需要将formControlName 添加到我的TR Component,特别是ng-select。但是,当我尝试添加 formControlName 时,它告诉我它需要在 formGroup 内。
据我所知,formGroup 在tasksComponent 中,并且正在包裹整个表格,因此从技术上讲它在formGroup 中?
我的最终目标是能够将 formControlName 添加到此输入中,但我很难找出到达那里的路径。
这是完整表单对象的图像。
最后一个扩展部分Role 是应该通过formControlName 调用此输入的内容,以便我可以执行验证以及控件上没有的内容。
更新
编辑 1 - @Harry Ninh 的更改
任务组件 HTML
<tbody>
<tr *ngFor="let t of intakeForm.get('tasks').controls let i = index; trackBy:trackByIndex" [taskTR]="t" [ui]="uiOptions" [intakeForm]="intakeForm" [taskIndex]="i" [formGroup]="intakeForm"></tr>
</tbody>
TR 组件 HTML
<td class="col-md-9">
<ng-select [items]="ui.adminRoles.options"
bindLabel="RoleName"
bindValue="Role"
placeholder="Select one or more roles"
[multiple]="true"
[clearable]="false"
formControlName="Roles"
(add)="addRole($event, row)"
(remove)="removeRole($event, row)">
</td>
结果:ERROR Error: formControlName must be used with a parent formGroup directive.
【问题讨论】:
-
我在您的代码中没有看到任何
[formGroup]="intakeForm。有什么遗漏吗? -
@HarryNinh - 所以这个例子中缺少 formGroup 但它被包含在内。它位于父组件中并包装了 tasksComponent。这就是它们传递给 tasksComponent 的内容。
标签: javascript angular typescript angular-reactive-forms