Angular2 No provider for ControlContainer when building a simple form

前端 未结 2 2104
情话喂你
情话喂你 2021-02-13 13:48

This is my form:

app.component.html

<
相关标签:
2条回答
  • 2021-02-13 14:29

    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

    • https://angular.io/docs/ts/latest/cookbook/dependency-injection.html#!#qualify-dependency-lookup-with-optional-and-host-

    • https://github.com/angular/angular/blob/master/modules/%40angular/common/src/forms/directives/ng_control_name.ts#L106

    0 讨论(0)
  • 2021-02-13 14:46

    Alternatively you can use the existing form from the parent by adding this to the child component declaration.

    viewProviders: [{provide: ControlContainer, useExisting: NgForm}]
    
    0 讨论(0)
提交回复
热议问题