Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic binding for FormControlName in Angular2

Tags:

angular

I am creating nested components. Having multiple formGroups I want to bind them dynamically. For eg.

forGroup in a component is like

formGroup : {
    controls:{
        firstName: FormControl,
        lastName: FormControl,
        userName: FormControl,
        Password: FormControl
    }
}

HTML is something like & it is for multiple controls..

<div [formGroup]='formGroup'>
    <div class="error-box">{{formGroup.controls.get('firstName').errors}}</div>

    <div *ngIf="formControl.firstName?.visible" [ngClass]="{'has-error': formControl.firstName.error}">
        <label>{{formGroup.controls.get('firstName').label}}</label>
        <input type="text" formControlName="firstName" [maxlength]="formContrl.firstName?.maxLength">
        <span class="error" *ngif="formControl.firstName.error"></span>
    </div>

    <div class="error-box">{{formGroup.controls.get('lastName').errors}}</div>

    <div *ngIf="formControl.lastName?.visible" [ngClass]="{'has-error': formControl.lastName.error}">
        <label>{{formGroup.controls.get('lastName').label}}</label>
        <input type="text" formControlName="lastName" [maxlength]="formContrl.lastName?.maxLength">
        <span class="error" *ngif="formControl.lastName.error"></span>
    </div>
</div>

I want to bind the controls in common component.

I tried this.

<text-input [group]="formGroup.controls.firstName" [formControls]="formControl.firstName"></text-input>

So I am creating common HTML but when I try to bind this its giving me error on binding the directive formControlName="formControls.name //withwhat I am passing"

like image 307
Sankalp Avatar asked Feb 16 '17 10:02

Sankalp


People also ask

Can we use two way data binding in reactive form?

We can perform Two way binding in Template driven forms but there is no two way binding in Reactive forms.

Can we use ngModel in reactive forms?

You can use [(ngModel)] with Reactive forms. This will a completely different directive than the one that would be used without the formControlName . With reactive forms, it will be the FormControlNameDirective . Without the formControlName , the NgModel directive would be used.

How do you bind data in reactive form?

Data binding in reactive forms For data interpolation recall how you will have to use the ng-bind directive to bind properties to values in the template, now all you have to do is to call the value and the reactive forms API will bind the data and display it for you.


1 Answers

Just ran into the same problem ...

You have to use [formControlName]="formControls.name" instead of formControlName="formControls.name".

More information here https://angular.io/docs/ts/latest/cookbook/dynamic-form.html.

like image 188
nhenrich Avatar answered Nov 13 '22 13:11

nhenrich