Search code examples
angularangular-forms

Got "No provider Exception" putting ngControl for sub-component


I want to implement custom form using Angular2 (with TypeScript and Jade).

When I used my-input element I created as custom form components instead of input and added ngControl directive to input, I got exception errors "No provider for ControlContainer!". Then, when I removed ngControl from input element, errors didn't occur but the form functions didn't work (e.g. validators).

Parent Component

@Component({
  selector: 'top-page',
  template: `
    <form [ngFormModel]="myForm">
      <my-input name="username" placeholder="username is here.">
    </form>
  `,
});
export class TopPageComponent { ... }

Sub-Component

@Component({
  selector: 'my-input',
  template: `
    <label class="custom-class-1">
      <div class="custom-class-2"></div>
      <input type="text" id="{{name}}" placeholder="{{placeholder}}" ngControl="{{name}}" [(ngModel)]="{{name}}">
    </label>
  `,
});
export class MyInputComponent { ... }

For trial, I append ngControlGroup directive to label element in my-input component, but getting errors. (Of course, wrote import Component, Input, etc... and @Input() in TypeScript files.)


Solution

  • I think that you should put a form tag into your sub component:

    <form>
      <label class="custom-class-1">
        <div class="custom-class-2"></div>
          <input type="text" id="{{name}}"
                 placeholder="{{placeholder}}"
                 ngControl="{{name}}" [(ngModel)]="{{name}}">
      </label>
    </form>