Search code examples
angularangular-formsangular-dependency-injection

Angular - useExisting ngForm optional


I need to inject the form from a parent component into a child component to be able to validate the child component input like so:

    <form #formReference="ngForm">
     <child-component></child-component>
     <child-component></child-component>
     <child-component></child-component>

     <p>{{formReference.form.valid}}</p>
    </form>

Right now i have added this provider on the child component to make it use the parent form and it works fine

@Component({
  selector: 'app-child-component',
  templateUrl: './child-component.component.html',
  styleUrls: ['./child-component.component.scss'],
  viewProviders: [ { provide: ControlContainer, useExisting: NgForm } ]
}) 

However i still need to be able to use the child component as before without a form. Is there a way to make this provider optional? At the moment if a use my child component without a form wrapping it i get the error

ERROR NullInjectorError: R3InjectorError(CustomModule)[NgForm -> NgForm -> NgForm -> NgForm -> NgForm]
  

Thanks for your time!


Solution

  • use useFactory method to provide optional dependency, by setting Optional flag in deps array

    @Component({
      selector: 'app-child-component',
      templateUrl: './child-component.component.html',
      styleUrls: ['./child-component.component.scss'],
      viewProviders: [
        {
          provide: ControlContainer,
          deps: [[Optional, NgForm]],
          useFactory: (ngForm: NgForm) => ngForm,
        },
      ],
    })