在Angular 2+中扩展FormControlDirective

问题描述 投票:1回答:1

我正在研究这个问题,试图弄清如何扩展FormControlDirective:Attempting to extend FormControlDirective to implement my own FormControl directive results in faulty binding

有一个答案,但是我不确定是什么意思:

formControl \ formControlName选择器又出现一个位置-the value accessor。为了使指令起作用,您应该实现所有默认值hybridFormControl指令的访问器(内置指令的模式)。

这是我的代码:

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;
  }
}

[@ ronif的问题与@ronif的Plunker非常相似。即使传递了set appControl之类的值,<input type="text" class="form-control" appControl="firstName">的确运行,即使FormControlDirective._rawValidators与标准FormGroup一起使用,FormControlDirective似乎始终是一个空数组。

我将如何实现“实现所有默认值访问器”?

我正在研究这个问题,试图弄清楚如何扩展FormControlDirective:尝试扩展FormControlDirective来实现我自己的FormControl指令会导致错误的绑定。 ...

angular angular-directive angular-reactive-forms angular-forms
1个回答
0
投票

如果其他人遇到类似问题,这是我想出的解决方案。我想根据子表单控件元素动态创建表单控件模型。这样一来,我不必编写具有大量表单控制字段的初始模型,而仍然可以获得反应式表单模型的好处。这是扩展FormControlName类的方法:

© www.soinside.com 2019 - 2024. All rights reserved.