【发布时间】:2019-08-29 01:35:41
【问题描述】:
注意:我正在寻找响应式表单方法的解决方案。模板驱动表单的解决方案已经here
我有一个具有反应式表单的库,我正在尝试使用 ng-template 和 ng-container(A 行)插入表单输入。
库组件
html
<form [formGroup]="mainForm">
<input type="text" formControlName="inside">
<ng-container [ngTemplateOutlet]="template"></ng-container> //line A
</form>
TS:
export class LibraryComponent implements OnInit {
@Input() template;
mainForm: FormGroup;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.mainForm = this.formBuilder.group({
inside: ['inside'],
outside: ['outside'],
});
}
}
应用组件
<app-library [template]="outer"></app-library>
<ng-template #outer>
<input type="text" formControlName="outside">
</ng-template>
执行此操作时,我收到 错误:
preview-d2335ca5bdb955611c1cb.js:1 ERROR Error: formControlName must be used with a parent formGroup directive. You'll want to add a formGroup
directive and pass it 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.ReactiveErrors.controlParentException (reactive_errors.ts:14)
at FormControlName._checkParentType (form_control_name.ts:272)
at FormControlName._setUpControl (form_control_name.ts:277)
at FormControlName.ngOnChanges (form_control_name.ts:207)
at checkAndUpdateDirectiveInline (provider.ts:208)
at checkAndUpdateNodeInline (view.ts:429)
at checkAndUpdateNode (view.ts:389)
at debugCheckAndUpdateNode (services.ts:431)
at debugCheckDirectivesFn (services.ts:392)
at Object.eval [as updateDirectives] (VM1408 AppComponent.ngfactory.js:41)
任何帮助将不胜感激。
【问题讨论】:
标签: angular angular-reactive-forms