【发布时间】:2021-02-28 18:54:35
【问题描述】:
我在表单上使用ng-select,但现在我想在自定义组件上包装它的特定配置。问题是我正在使用包含其中几个的FormArray,在下一个方式:
this.profileForm = this.formBuilder.group(
{
...
linkedRoles: this.formBuilder.array([])
}
);
这个linkedRoles 被下一个FormGroup 填充:
let fgRoles: FormGroup;
for (let i = 0; i < this.userRoles.length; i++) {
fgRoles = this.formBuilder.group({
activeRole: [{ value: null }],
roles: [{ value: null }]
});
this.linkedRoles.push(fgRoles);
this.linkedRoles.controls[i].setValue({
activeRole: this.userRoles[i].role,
roles: this.extractUserRoles(this.userRoles[i])
});
为了简单起见,也创建了一个 getter:
get linkedRoles(): FormArray {
return <FormArray>this.profileForm.get("linkedRoles");
}
在此之后,在我的模板中,我使用了这个完美的作品:
<form [formGroup]="profileForm">
...
<table>
...
<tbody>
<tr formArrayName="linkedRoles"
*ngFor="let usuR of userRoles;
let idx = index"
>
...
<td data-label="Roles" [formGroupName]="idx">
<ng-select #rolesNgSelect
[hideSelected]="false"
bindLabel="rol"
...
formControlName="roles"
>
<ng-template ng-label-tmp let-item="item">
...
</ng-template>
<ng-template ng-option-tmp let-item="item">
...
</ng-template>
</ng-select>
</td>
</tr>
</tbody>
</table>
</form>
现在,我试图用我的自定义组件role-selector 替换ng-select,它基本上从ng-select 接收所有必要的属性并将其包装在模板中。我之前的模板的变化如下:
<tr formArrayName="linkedRoles"
*ngFor="let usuR of userRoles;
let idx = index;
let ctrlRol of linkedRoles.controls"
>
<td>
<app-role-selector
[hideSelected]="false"
bindLabel="rol"
...
formControlName="roles"
>
</app-role-selector>
</td>
</tr>
有了这个细微的变化,我在控制台中收到了下一个错误:
ERROR Error: No value accessor for form control with path: 'linkedRoles -> 0 -> roles'
最奇怪的是,当我单击出现的无样式框时,它加载并几乎可以正常工作。我应该将我的formControlName 标记移动到组件模板中的ng-select 吗?
可能的解决方案
正在寻找解决方案,I found the interesting ngDefaultControl。将此指令添加到我的自定义组件使其按预期运行。现在看起来像这样:
<app-role-selector
[hideSelected]="false"
bindLabel="rol"
...
ngDefaultControl
formControlName="roles"
>
唯一的反面是我不完全理解为什么这是必要的,如果这是最好的解决方案。
【问题讨论】:
标签: angular formarray form-control angular-ngselect