更新时间:2022-10-17 22:14:50
您可以使用 ngFormControl
指令代替 ngControl
并将控制变量传递给子 Input
像这样:
子组件
@Component({选择器:'我的孩子组件',模板:`<input type="text" [ngFormControl]="control">`,指令:[FORM_DIRECIVES]})导出类子{@Input() 控制:控制;}
另见 plunkr https://plnkr.co/edit/ydRAOmFG6FU6lxTonWzj?p=preview一个>
NgControl 指令是子模板中必需的表单标签
另见
This is my form:
app.component.html
<form [ngFormModel]="myForm">
<my-child-component></my-child-component>
</form>
app.component.ts
constructor ( private _formBuilder : FormBuilder ) {
this.myForm = _formBuilder.group( {
firstName : ["",Validators.required]
} );
}
my-child-component:
<input type="text" ngControl="firstName">
Error:
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
and FORM_PROVIDERS
are being injected at the top app level. I've done exactly everything as per their guides.
I also tried adding FORM_DIRECTIVES
to the child or to app.component with no success.
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
@Component({
selector: 'my-child-component',
template: `
<input type="text" [ngFormControl]="control">
`,
directives: [FORM_DIRECTIVES]
})
export class Child {
@Input() control: Control;
}
See also plunkr https://plnkr.co/edit/ydRAOmFG6FU6lxTonWzj?p=preview
NgControl directive is required form tag within Child template
See also