注意:我正在寻找反应式方法的解决方案。模板驱动窗体的解决方案已经是https://stackoverflow.com/questions/46849570/cloned-elements-cannot-be-submitted-in-angular4/46863758#46863758
我有一个库,它有一个反应性表单,我试图使用ng模板和ng容器插入表单输入(A行)。
LibraryComponent
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'],
});
}
}
AppComponent
<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)
任何帮助都会得到极大的重视。
发布于 2019-08-28 09:35:22
真的,我不知道你想做什么,但简单的传递为ngTemplateOutletContext的表单,并使用let获取它
你的library.component
<ng-container [ngTemplateOutlet]="template"
[ngTemplateOutletContext]="{form:mainForm}">
</ng-container>
你的模板
<ng-template #outer let-form=form>
<input type="text" [formControl]="form.get('outside')">
</ng-template>
确保我们使用的是[formControl]
而不是formControlName
,这是因为我们需要传递表单
发布于 2019-08-28 09:35:41
使用context.Then将context.Then实例传递给ng-模板,在ng-模板中使用formControl而不是formControlName。
App.component.html
<app-library [template]="outer"></app-library>
<ng-template #outer let-control="control">
<input type="text" [formControl]="control">
</ng-template>
lib.component.html
<form [formGroup]="mainForm">
<input type="text" formControlName="inside">
<ng-container *ngTemplateOutlet="template; context:{control: mainForm.get('outside')}"></ng-container>
</form>
https://stackoverflow.com/questions/57696840
复制