【发布时间】:2018-09-01 13:12:51
【问题描述】:
我正在看这个问题,试图弄清楚如何扩展 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 的Plunker 非常相似。 set appControl 确实运行,即使我传递了像 <input type="text" class="form-control" appControl="firstName"> 这样的值,而 FormControlDirective._rawValidators 似乎总是一个空数组,即使 FormGroup 与标准 FormControlDirective 一起使用。
我将如何“实现所有默认值访问器”?
【问题讨论】:
标签: angular angular-directive angular-reactive-forms angular-forms