0
votes

Does anybody know if there is a way to extend or implement NgModel directive? I would like to have a custom directive that works in the same way, but also has some extra features for my template-driven form.

It is possible to achieve the result I need by creating a directive only for the feature in question and adding ngModel to the input field, but I wonder if it's possible to have just one directive for both.

In particular, I need my custom directive to enable validation (without ngModel attributes like required do not work).

So far, I have tried extending NgModel, but I am unable to inject all the required dependencies in my constructor to pass them to super:

export class ReplaceNgModelDirective extends NgModel {

  constructor(
    @Optional() @Host() parent: ControlContainer,
    @Optional() @Self() @Inject(NG_VALIDATORS) validators: (Validator|ValidatorFn)[],
    @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) asyncValidators: (AsyncValidator|AsyncValidatorFn)[],
    @Optional() @Self() @Inject(NG_VALUE_ACC) valueAccessors: ControlValueAccessor[],
    @Optional() @Inject(ChangeDetectorRef) changeDetectorRef?: ChangeDetectorRef|null
  ) {
    super(parent, validators, asyncValidators, valueAccessors, changeDetectorRef);
  }

The validators array is always null, if I remove @Optional it throws NG0201: No provider for InjectionToken NgValidators error. What's strange is that when I add ngModel to input together with the custom directive (<input type="number" id="amount" name="amount" class="form-control" replaceNgModel ngModel required pattern="^[1-9]+[0-9]*$">) the error disappears and validators are injected without any problem into my ReplaceNgModelDirective.

I am also always getting Error: No value accessor for form control with name: 'amount' and valueAccessors array injected in the constructor is constantly null as well.

The control property of NgModel is inherited well and has the correct name, but it is always valid and doesn't have validators unless I add ngModel to the field.

Any ideas? I didn't find any posts about ngModel inheritance in the Internet, is that even possible?