我想从附加到我的指令的输入的控件传递我,但我得到以下错误'NullInjectorError:没有FormControl的提供程序!'。
基本上我正在尝试创建一个监视另一个输入的验证器,并确保我们输入的值总是小于或等于。
我知道还有其他方法可以做到这一点,但我想将其作为验证器实现,并将formcontrol注入输入中的验证字段。我已经包含了组件,指令和模块代码(如果有帮助的话)以及stackblitz链接到示例。 https://stackblitz.com/edit/angular-material2-issue-zxb1t2
组件html代码:
<div>
<input
required
placeholder="total"
[formControl]="total">
<div *ngIf="total.invalid">{{getErrors(total)}}</div>
<input
required
[lessThanInput]="total"
placeholder="less than total"
[formControl]="lessThanTotal">
<div *ngIf="lessThanTotal.invalid">{{getErrors(lessThanTotal}}</div>
指令代码:
import { FormControl, NG_VALIDATORS, Validator, ValidatorFn} from
"@angular/forms";
import {
AfterContentInit,
Directive, ElementRef,
Input,
} from "@angular/core";
@Directive({
selector: '[lessThanInput]',
providers: [
{
provide: NG_VALIDATORS,
useExisting: LessThanOtherControl,
multi: true
}
]
})
export class LessThanOtherControl implements Validator {
validator: ValidatorFn;
@Input() lessThanInput:FormControl;
@Input() otherControlName: string;
subscription: any;
//if i remove fc:Formcontrol the error goes away but i cannot then access the form control through the constructor. Is this even possible? iIthought it was.
constructor(private el: ElementRef, private fc: FormControl) {
console.log(fc);
this.validator = this.validateLessThanOther;
this.lessThanInput.valueChanges.subscribe(this.fc.updateValueAndValidity);
}
validate(c: FormControl) {
return this.validator(c);
}
validateLessThanOther(control: FormControl) {
if (control && control.value) {
if (isNaN(+control.value) || isNaN(+this.lessThanInput.value)) {
return null;
}
const isValid = +control.value <= +this.lessThanInput.value;
return isValid ? null : {
'biggerThanOtherField': {
value: control.value,
otherInputName: this.otherControlName
}
};
}
return null;
}
}
模块代码:
@NgModule({
imports: [
BrowserModule,
CommonModule,
MaterialModule,
FormsModule,
ReactiveFormsModule,
BrowserAnimationsModule
],
declarations: [
AppComponent,
LessThanOtherControl,
],
bootstrap: [AppComponent],
providers: []
})