Search code examples
angularbindingngmodel

formControl and ngModel


I have the following code on angular

<div *ngFor="let student of students.controls; let i=index" [formGroupName]="i" [class.active]="student.checked">
    <!-- The repeated address template -->
    <h4>Student #{{i + 1}}
        <input type="checkbox" formControlName="checked" [(ngModel)]="student.checked">
    </h4>
    <div class="form-group">
        <label class="center-block">First Name:
            <input class="form-control" formControlName="firstName">
        </label>
    </div>
    <div class="form-group">
        <label class="center-block">Last name:
        <input class="form-control" formControlName="lastName">
        </label>
    /div>
</div>

here is my css

div.active{
  background-color:#CCFFCC !important;
}

at this line

The problem is when the checkBox is checked the background color of my array element containing the checkbox become green as I want but the formControlName "checked" is not taken into account and when I delete [(ngModel)]="student.checked" I don't have the background color changing behaviour anymore but the formControlName "checked" works

Actual behaviour, I build my array with an imported student having the properties checked true, the box is not checked but when I check it the background become green

Wanted behaviour : I build my array with an imported student having the properties checked true, the box is checked and when I uncheck it the green background disappear (my ngModel [(ngModel)]="student.checked" is bind with the formControlName "checked")


Solution

  • I've found the solution

    <div *ngFor="let student of students.controls; let i=index" 
    [formGroupName]="i" [class.active]="student.controls.checked.value>
        <!-- The repeated address template -->
        <h4>Student #{{i + 1}}
            <input type="checkbox" formControlName="checked">
        </h4>
    

    This code works

    Thanks for the help.