本文介绍了尝试扩展FormControlDirective来实现我自己的FormControl指令会导致错误的绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图颠倒表单控件将自身注册到FormGroup的方式,以便不必

I'm trying to inverse the way forms controls are registering themselves onto a FormGroup, so that instead of having to

@Component({..., template: `<input [formControl]="myControl"`}    
...

@Component({..., template: `<input [formControName]="myControlName"`}    
...

我可以

@Component({..., template: `<input myFormControl`}    
...

让我的指令为我创建并添加FormControl.

And have my directive create and add the FormControl for me.

最好对此 Plunker 进行解释.

It is best explained with this Plunker.

似乎不起作用的是将视图绑定到表单模型,如您所见,更改输入不会更改表单模型值.

What doesn't seem to work is the binding the view to the form model, as you can see, changing the the input does not change the form model value.

调试表明没有valueAccessor注入到构造函数中(不同于直接使用基FormControlDirective类时的情况).

Debugging it shows that there are no valueAccessor injected to the constructor (unlike when using the base FormControlDirective class directly).

如果您想知道,我的最终目标是拥有一个父定制的组组件,该组件将@ViewChildren(MyFormDirective)并动态地将它们全部添加到其创建的表单中.

If you're wondering, my end goal would be that I would have a parent customized group component that would @ViewChildren(MyFormDirective), and dynamically add them all to it's created form.

推荐答案

您快到了.不过,还有另外一招.该输入元素没有DefaultValueAccessor,因此构造函数参数填充为null值.

You are almost there. There is one more trick though. There isn't DefaultValueAccessor for that input element, thus constructor arguments are populate with null value.

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

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).

P.S我相信您指令的提供者应该更正为

P.S I believe the provider of your directive should be corrected to

providers: [{
    provide: NgControl, //<-- NgControl is the key
    useExisting: forwardRef(() => HybridFormControlDirective)
}]

这篇关于尝试扩展FormControlDirective来实现我自己的FormControl指令会导致错误的绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 17:58