Angular - useExisting ngForm 可选

Mir*_*rco 3 angular angular-forms angular-dependency-injection

我需要将表单从父组件注入到子组件中,以便能够验证子组件输入,如下所示:

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

     <p>{{formReference.form.valid}}</p>
    </form>
Run Code Online (Sandbox Code Playgroud)

现在我已经在子组件上添加了这个提供程序,使其使用父表单并且工作正常

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

但是,我仍然需要能够像以前一样在没有表单的情况下使用子组件。有没有办法让这个提供者可选?目前,如果在没有表单包装的情况下使用我的子组件,我会收到错误

ERROR NullInjectorError: R3InjectorError(CustomModule)[NgForm -> NgForm -> NgForm -> NgForm -> NgForm]
  
Run Code Online (Sandbox Code Playgroud)

谢谢你的时间!

Che*_*pan 6

使用 useFactory 方法通过在 deps 数组中设置可选标志来提供可选依赖项

@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,
    },
  ],
})
Run Code Online (Sandbox Code Playgroud)