Extending FormControlDirective in Angular 2+

限于喜欢 提交于 2019-12-11 04:58:00

问题


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'?

来源:https://stackoverflow.com/questions/49439836/extending-formcontroldirective-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!