Angular2构建简单表单时没有ControlContainer的提供程序 [英] Angular2 No provider for ControlContainer when building a simple form
问题描述
这是我的表格:
app.component.html
app.component.html
<form [ngFormModel]="myForm">
<my-child-component></my-child-component>
</form>
app.component.ts
app.component.ts
constructor ( private _formBuilder : FormBuilder ) {
this.myForm = _formBuilder.group( {
firstName : ["",Validators.required]
} );
}
我的孩子的组件:
<input type="text" ngControl="firstName">
错误:
No provider for ControlContainer
[ERROR ->]<md-input
ngControl="firstName"
placeholder="First name">
如果我将输入移动到应用程序组件内部,则可以使用,但是我的输入位于子组件内部.
If I move the input inside the app component itself, it'll work, but my input is inside a child component.
FORM_DIRECTIVES
和FORM_PROVIDERS
在最高应用程序级别被注入.我已经按照他们的指南做了所有事情.
FORM_DIRECTIVES
and FORM_PROVIDERS
are being injected at the top app level. I've done exactly everything as per their guides.
我还尝试将FORM_DIRECTIVES
添加到子级或app.component中,但没有成功.
I also tried adding FORM_DIRECTIVES
to the child or to app.component with no success.
推荐答案
您可以使用ngFormControl
指令而不是ngControl
,只需将控制变量传递给子级Input
,就像这样:
You can use ngFormControl
directive instead of ngControl
and just pass control variable into child Input
like this:
<form [ngFormModel]="myForm">
<my-child-component [control]="myForm.controls.firstName"></my-child-component>
</form>
Child.component
Child.component
@Component({
selector: 'my-child-component',
template: `
<input type="text" [ngFormControl]="control">
`,
directives: [FORM_DIRECTIVES]
})
export class Child {
@Input() control: Control;
}
另请参阅plunkr https://plnkr.co/edit/ydRAOmFG6FU6lxTonWzj?p=preview
See also plunkr https://plnkr.co/edit/ydRAOmFG6FU6lxTonWzj?p=preview
NgControl指令是子模板中必需的表单标记
NgControl directive is required form tag within Child template
另请参见