Angular 6 - 无法在验证器指令中注入 NgControl

Angular 6 - can't inject NgControl in validator directive

我在创建要在模板驱动表单中使用的自定义验证器时遇到问题。我想构造函数注入宿主元素的 NgControl,它也有一个 NgModel 指令。但我不断收到以下 Angular 编译错误:

ERROR in : Cannot instantiate cyclic dependency! NgModel ("
        <div>
                <label for="name">Your name</label>
                [ERROR ->]<input id="name" type="text" name="name" #name="ngModel" ngModel [requiredIfCondition]="toggleBool" r")

我的指令 class 如下所示:

import { Directive, forwardRef, Injector, Input, Self } from '@angular/core';
import { AbstractControl, NG_VALIDATORS, NgControl, Validator } from '@angular/forms';

@Directive({
    selector: '[requiredIf][ngModel]',
    providers: [
        { provide: NG_VALIDATORS, useExisting: forwardRef(() => RequiredIfDirective), multi: true },
    ],
})
export class RequiredIfDirective implements Validator {
    private innerRequiredIfCondition: boolean = false;
    @Input()
    public set requiredIfCondition(val: boolean) {
        this.innerRequiredIfCondition = val;
        let hostControl: AbstractControl | null = this.ngControl.control;
        if (hostControl !== null) {
            hostControl.updateValueAndValidity();
        }
    }

    public constructor(@Self() private readonly ngControl: NgControl) {
    }

    public validate(c: AbstractControl): {[error: string]: string} | null {
        if (this.innerRequiredIfCondition && (c.value === null || c.value === '')) {
            return {
                requiredIf: 'In this context this field is required.',
            };
        }
        return null;
    }
}

我正在这样应用指令:

<div>
    <label for="name">Your name</label>
    <input id="name" type="text" name="name" #name="ngModel" ngModel [requiredIfCondition]="toggleBool" requiredIf />
    <div *ngIf="name.errors && name.errors.requiredIf" class="red-text text-darken-3">
        Name is required now.
    </div>
</div>

我会尝试手动注入 NgControl,但由于它是抽象的 class 我认为您不能再这样做了。

我也尝试过注入 AbstractControl 而不是 NgControl,但是系统找不到 AbstractControl 的提供者。

我似乎无法在模板驱动表单的上下文中找到更多关于此的信息,所以我非常感谢任何关于如何解决此问题的想法。

提前致谢, 约书亚

没有找到解决方案,但确实找到了解决方法:通过注入器。

public constructor(
  private injector: Injector
  @Self() private readonly ngControl: NgControl = this.injector.get(NgControl),
) {}

编辑

只需从指令本身中删除提供程序,并改为在模块中提供它。

Stackblitz