Trying to extend FormControlDirective to implement my own FormControl directive results in erroneous binding

I am trying to change the way I manage forms by registering with FormGroup

so that instead of

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

      

Or

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

      

I could

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

      

And create my directive and add FormControl

for me.

This is best explained with Plunker .

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

Debugging shows that the constructor doesn't valueAccessor

(as opposed to using the base class FormControlDirective

).

In case you're wondering, my end goal would be for me to have a parent custom group component that @ViewChildren(MyFormDirective)

dynamically adds them all to the generated form.

+3


source to share


1 answer


You're almost there. There is one more trick, however. There is no input for this element DefaultValueAccessor

, so the constructor arguments are filled with a value null

.

Selectors formControl

\ formControlName

appear in one more place - the value attribute . For your directive to work, you must implement all of the directive's default value attributes hybridFormControl

(following the pattern for inline directives).



PS I believe the vendor of your directive should be fixed for

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

      

+2


source







All Articles