Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding NgModel to FormControl in new Angular 2 forms

I am currently converting my Angular 2 forms to the recently introduced Form API, but I'm having trouble hooking up inputs nested in a directive to the controls defined in the FormGroup.

I define the form and validation in the component for the form like this (in Typescript):

model = {
   foo: 12.34
}

amount: : FormControl = new FormControl('', Validators.required);

ngOnInit() {
    this.fooFormGroup = new FormGroup({
        amount: this.amount,
      });    
    this.form.addControl("formGroup", this.formGroup);
}

In the HTML, I hook up the form to the inputs with the name-property. This works, except when I use a custom directive which embeds an input like this:

<fieldset>
    <form [formGroup]="fooFormGroup ">
         <custom-input-for-decimals [decimals]="4" [value]="model.amount" (valueChange)="model.amount = $event" controlname="amount"></custom-input-for-decimals>
    </form>
</fieldset>

In the directive, I update and pre-format the ngModel values (cut off decimals beyond 4, for example). It takes a controlname property which is set as a name attribute in the template:

template: '<input type="text" [(ngModel)]="inputValue" (blur)="onBlur()" name="{{controlname}}">'

But this does not create a hook between the formcontrol and the ngModel. Only when adding an additional hidden input next to where I use the directive, in the same component as the formGroup-tag, it works. But this seems a bit redundant. Is there are better solution?

NB: Passing the FormControl to the directive and using the name of that form control property didn't work either. Nesting the input in a form of its own does not seem even more verbose than the hidden input.

like image 785
Erwin Bergervoet Avatar asked Sep 15 '25 12:09

Erwin Bergervoet


1 Answers

I solved it by passing the control itself to the directive and using [formControl]="control" to hook it to the input.

like image 57
Erwin Bergervoet Avatar answered Sep 17 '25 04:09

Erwin Bergervoet