指令会导致绑定错误

指令会导致绑定错误

本文介绍了尝试扩展 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 指令会导致绑定错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 01:26