我正在尝试使用动态输入制作反应形式
所以我像这样创建了反应式表单组件
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>
</div>
</form>
并创建了附加到 div 的指令operationClass并将组件注入到div
operationClass.directive.ts
constructor(private el: ElementRef, private render: Renderer2, private viewContainerRef: ViewContainerRef,
private componentFactory: ComponentFactoryResolver) {}
ngOnInit(): void {
var comRef = this.componentFactory.resolveComponentFactory(input_component);
var _comRef = this.viewContainerRef.createComponent(comRef);
_comRef.instance.formControlName = this._formControlName;
_comRef.instance.type = this.type;
}
并且该组件通过获取formControlNameandtype并在自定义条件下呈现输入来呈现正确的输入
并且用于呈现输入的组件是: 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)