【发布时间】:2019-10-30 22:09:59
【问题描述】:
我在创建要在模板驱动表单中使用的自定义验证器时遇到问题。我想构造函数注入宿主元素的 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")
我的指令类如下所示:
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,但由于它是一个抽象类,我认为你不能再这样做了。
我也尝试过注入 AbstractControl 而不是 NgControl,但系统找不到 AbstractControl 的提供者。
我似乎无法在模板驱动表单的上下文中找到更多关于此的信息,因此我非常感谢有关如何解决此问题的任何想法。
提前致谢, 约书亚
【问题讨论】:
-
对了,用 [(ngModel)]="SomeProperty" 代替 ngModel 的应用也没有用...
标签: angular typescript angular-directive