这是我的表格:
app.component.html
<form [ngFormModel]="myForm">
<my-child-component></my-child-component>
</form>
Run Code Online (Sandbox Code Playgroud)
app.component.ts
constructor ( private _formBuilder : FormBuilder ) {
this.myForm = _formBuilder.group( {
firstName : ["",Validators.required]
} );
}
Run Code Online (Sandbox Code Playgroud)
我的孩子组分:
<input type="text" ngControl="firstName">
Run Code Online (Sandbox Code Playgroud)
错误:
No provider for ControlContainer
[ERROR ->]<md-input
ngControl="firstName"
placeholder="First name">
Run Code Online (Sandbox Code Playgroud)
如果我在app组件本身内移动输入,它会工作,但我的输入是在子组件内.
FORM_DIRECTIVES而FORM_PROVIDERS在顶部的应用程序级别被注入.我按照他们的向导完成了一切.
我也试过添加FORM_DIRECTIVES到孩子或app.component没有成功.
您可以使用ngFormControl指令而不是ngControl将控制变量传递给子,Input如下所示:
<form [ngFormModel]="myForm">
<my-child-component [control]="myForm.controls.firstName"></my-child-component>
</form>
Run Code Online (Sandbox Code Playgroud)
Child.component
@Component({
selector: 'my-child-component',
template: `
<input type="text" [ngFormControl]="control">
`,
directives: [FORM_DIRECTIVES]
})
export class Child {
@Input() control: Control;
}
Run Code Online (Sandbox Code Playgroud)
另见plunkr https://plnkr.co/edit/ydRAOmFG6FU6lxTonWzj?p=preview
NgControl指令是Child模板中必需的表单标记
也可以看看