小编Mir*_*rco的帖子

Angular - useExisting ngForm 可选

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

    <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)

谢谢你的时间!

angular angular-forms angular-dependency-injection

3
推荐指数
1
解决办法
1496
查看次数