Angular2 在构建简单表单时没有 ControlContainer 的提供者 [英] Angular2 No provider for ControlContainer when building a simple form

查看:31
本文介绍了Angular2 在构建简单表单时没有 ControlContainer 的提供者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的表格:

app.component.html

<my-child-component></my-child-component></表单>

app.component.ts

构造函数(私有_formBuilder:FormBuilder){this.myForm = _formBuilder.group( {名字:["",Validators.required]});}

我的子组件:

 

错误:

 ControlContainer 没有提供者[错误 ->]

如果我在应用组件内部移动输入,它会工作,但我的输入在子组件内.

FORM_DIRECTIVESFORM_PROVIDERS 正在顶级应用级别注入.我完全按照他们的指南做了所有的事情.

我也尝试将 FORM_DIRECTIVES 添加到 child 或 app.component 中,但没有成功.

解决方案

您可以使用 ngFormControl 指令代替 ngControl 并将控制变量传递给子 Input 像这样:

<my-child-component [control]="myForm.controls.firstName"></my-child-component></表单>

子组件

@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

这篇关于Angular2 在构建简单表单时没有 ControlContainer 的提供者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆