Issue
I wrote my own custom form element DateInputComponent
by implementing ControlValueAccessor
and use it like this:
<my-date-input ngControl="date"></my-date-input>
From what I understand, ngControl
is syntactic sugar for [ngFormControl]="myControlGroup.controls['date']"
.
Now, inside my DateInputComponent
I would like to access the NgFormControl
.
I tried to bind it with @Input NgFormControl ngFormControl;
but it never gets set, and I tried injecting it with DateInputComponent(NgFormControl ngFormControl)
but that fails because there is no provider.
What is the correct approach to get it?
(Maybe I’m also approaching it the wrong way… I’d like for this DateInputComponent
to be able to display all validation errors by itself that might occur.)
Solution
I got it to work with the solution this comment suggest: by injecting the Injector
and reading the NgControl
out of it:
class DateInputComponent implements ControlValueAccessor, AfterViewInit {
Injector _injector;
DateInputComponent(this._injector);
NgControl control;
@override
ngAfterViewInit() {
control = _injector.get(NgControl).control;
}
}
Directly injecting the NgControl
, as Ted suggested, doesn’t work, because it causes a cyclic dependency.
Trying to access the NgControl
in the constructor won’t work, because it’s not available yet.
Answered By – enyo
Answer Checked By – Marie Seifert (FlutterFixes Admin)