Angular响应式表单动态输入组件报formControlName关联formGroup错误
Angular 动态注入响应式表单项绑定失效问题
现有实现结构
我计划开发带动态输入项的Angular响应式表单,当前基础代码结构如下:
main_component.ts
constructor(private formBuilder: FormBuilder) { this.operationGroupForm = this.formBuilder.group({ 'operation': '', 'searchTerm': '' }); }
main_component.html
<form [formGroup]="operationGroupForm"> <input type="text" formControlName="operation"> <div operationClass [type]="'mycustomtype'" [_formControlName]="'searchTerm'"> </div> </form>
注:原代码存在多余的闭合
</div>标签
我编写了附加在div元素上的operationClass指令,用于向该div内动态注入组件,指令代码如下:
operationClass.directive.ts
constructor(private el: ElementRef, private render: Renderer2, private viewContainerRef: ViewContainerRef, private componentFactory: ComponentFactoryResolver) {} ngOnInit(): void { const comRef = this.componentFactory.resolveComponentFactory(input_component); const _comRef = this.viewContainerRef.createComponent(comRef); _comRef.instance.formControlName = this._formControlName; _comRef.instance.type = this.type; }
注入的组件会根据传入的formControlName和type参数,按自定义条件渲染对应类型的输入框,相关代码如下:
input_component.ts
@Input() formControlName: string; @Input() type: string; constructor() {} ngOnInit(): void {}
input_component.html
<ng-container *ngIf="type"> <ng-container [ngSwitch]="type"> <ng-container *ngSwitchCase="'mycustomtype'"> <input type="text" [formControlName]="formControlName" class="form-control" /> </ng-container> <ng-container *ngSwitchDefault> <input type="number" [formControlName]="formControlName" class="form-control" /> </ng-container> </ng-container> </ng-container>
报错信息
目前核心问题为:内部输入框绑定的formControlName无法感知到外层的formGroup实例,控制台抛出如下错误:
ERROR Error: formControlName must be used with a parent formGroup directive. You'll want to add a formGroup directive and pass it to an existing FormGroup instance (you can create one in your class). Example: <div [formGroup]="myGroup"> <input formControlName="firstName"> </div> In your class: this.myGroup = new FormGroup({ firstName: new FormControl() }); at Function.controlParentException (forms.js:1692) at FormControlName._checkParentType (forms.js:6059) at FormControlName._setUpControl (forms.js:6063) at FormControlName.ngOnChanges (forms.js:5995) at FormControlName.rememberChangeHistoryAndInvokeOnChangesHook (core.js:2131) at callHook (core.js:3042) at callHooks (core.js:3008) at executeInitAndCheckHooks (core.js:2960) at refreshView (core.js:7331) at refreshEmbeddedViews (core.js:8408)
解决方案
报错核心原因:动态创建的组件存在独立的依赖注入边界,无法自动继承<form>标签上formGroup指令提供的表单上下文,导致内部的formControlName检测不到合法的父级formGroup。
调整步骤:
- 修改
operationClass指令,注入ControlContainer获取当前外层的FormGroup实例import { ControlContainer, FormGroup } from '@angular/forms'; constructor( private el: ElementRef, private render: Renderer2, private viewContainerRef: ViewContainerRef, private componentFactory: ComponentFactoryResolver, // 新增依赖注入 private controlContainer: ControlContainer ) {} - 动态注入
input_component时,把外层的FormGroup作为输入属性传递进去ngOnInit(): void { const comRef = this.componentFactory.resolveComponentFactory(input_component); const _comRef = this.viewContainerRef.createComponent(comRef); _comRef.instance.formControlName = this._formControlName; _comRef.instance.type = this.type; // 新增传递表单实例 _comRef.instance.parentFormGroup = this.controlContainer.control as FormGroup; } - 改造
input_component,接收传入的FormGroup并绑定到模板根节点
先在组件类新增输入属性:
再调整模板结构,把// input_component.ts import { FormGroup } from '@angular/forms'; @Input() formControlName: string; @Input() type: string; @Input() parentFormGroup!: FormGroup; // 新增接收表单实例 constructor() {}[formGroup]绑定到组件根节点:<!-- input_component.html --> <ng-container [formGroup]="parentFormGroup" *ngIf="type"> <ng-container [ngSwitch]="type"> <ng-container *ngSwitchCase="'mycustomtype'"> <input type="text" [formControlName]="formControlName" class="form-control" /> </ng-container> <ng-container *ngSwitchDefault> <input type="number" [formControlName]="formControlName" class="form-control" /> </ng-container> </ng-container> </ng-container>
场景补充:如果是多层嵌套动态表单的复杂场景,也可以在创建组件时自定义注入器,把
ControlContainer实例直接注入到动态组件的依赖树中,免去逐层传递表单实例的冗余代码。
内容的提问来源于stack exchange,提问作者Hassan Ahmed
相关产品推荐
相关产品推荐

