Attempting to extend FormControlDirective to implement my own FormControl directive results in faulty binding

风格不统一 提交于 2019-11-30 16:16:38

问题


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"`}    
...

Or

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

I could

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

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

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.

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

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.


回答1:


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.

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 I believe the provider of your directive should be corrected to

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


来源:https://stackoverflow.com/questions/44812220/attempting-to-extend-formcontroldirective-to-implement-my-own-formcontrol-direct

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