-->

Extending FormControlDirective in Angular 2+

2019-08-10 07:49发布

问题:

I'm looking at this question, trying to figure out how to extend FormControlDirective: Attempting to extend FormControlDirective to implement my own FormControl directive results in faulty binding.

There is an answer, but I'm not sure what is meant by:

The formControl \ formControlName selectors appear in one more place - the value accessor. In order your directive to work you should implement all default value accessors for the hybridFormControl directive ( following the pattern for the built-in directives).

Here is my code:

export const formControlBinding: any = {
  provide: NgControl,
  useExisting: forwardRef(() => ControlDirective)
};

@Directive({
  selector: '[appControl]',
  providers: [formControlBinding],
  exportAs: 'ngForm'
})
export class ControlDirective extends FormControlDirective implements OnInit {

  constructor(
    @Optional() @Self() @Inject(NG_VALIDATORS) validators: Array<Validator|ValidatorFn>,
    @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) asyncValidators: Array<AsyncValidator|AsyncValidatorFn>,
    @Optional() @Self() @Inject(NG_VALUE_ACCESSOR) valueAccessors: ControlValueAccessor[],
    public renderer: Renderer2,
    public hostElement: ElementRef,
  ) {
    super(validators, asyncValidators, valueAccessors);
  }

  @Input() set appControl(form: FormControl) {
    console.log(form);
    this.form = form;
  }
}

It is very similar to @ronif's Plunker from his question. set appControl does run, even though I'm passing a value like <input type="text" class="form-control" appControl="firstName">, and FormControlDirective._rawValidators seems to always be an empty array, even though the FormGroup works with the standard FormControlDirective.

How would I go about 'implementing all default value accessors'?