lundi 7 août 2017

checkbox does not retain state in angular 2

Dear StackOverflow community I am facing an issue with checkbox in Angular2 ngFor

I have an array of users where each user contains a boolean flag. I bind the flag with checkbox which works fine in ngFor. The issue is when I dynamically add another use in the array the already checked items lose their checked state and becomes unchecked.

Here is HTML

<div class="checkbox mtx" *ngFor="let user of project.users;let $userIndex = index;">
 <input 
    type="checkbox" id="" name="canGiveFeedback"
      [checked]="user.can_give_feedback"
      [ngModel]="user.can_give_feedback"
      (change)="user.toggleFlag()"
 />
    <label class="mts" for="">Can give feedback</label>
</div>

Here is how I tried to fix. I assign ngFor index as id to each checkbox then on add new user, I push new user in user's array, loop the array and fire click event by referring the id I set in the template.

On add new user i call this function

retainCheckboxState() {
    var me:any = this;
    setTimeout(function () {
        me.users.forEach(function (user:User,index:any) {
            if(user.can_give_feedback) {
                $('#' + index).click();
            }
        });
    },10);
} 

Kindly suggest some better solution for this. Thx in advance.




Aucun commentaire:

Enregistrer un commentaire