简体   繁体   中英

Why is mat-checkbox inside *ngFor not getting the latest [checked] value from model?

<ng-container *ngFor="let item of items">
     >>>>>>>>LINE 2>>>>>>>>>> {{item.checkedOrUnchecked}}
     <mat-checkbox [checked]="item.checkedOrUnchecked"></mat-checkbox>

LINE 2 in above code is always in sync with changes done else-where.

However, mat-checkbox is not updated with true/false. Its losing the context here. Even if *ngFor is creating a child-context for every iteration, when LINE 2 is able to pick the latest updates why is mat-checkbox not able to be in sync.

One thing I noticed is, if the initial value of item.checkedOrUnchecked is false and if it is changed to true, mat-checkbox is checked. But, further toggling of item.checkedOrUnchecked from true-to-false or false-to-true doesn't have any affect.

Issue can be replicated here https://stackblitz.com/edit/angular-material2-checkbox-issue-zyjhd3

Plz can someone advise.

Change this :

[checked]="item.checkedOrUnchecked"

to

[(ngModel)]="item.checkedOrUnchecked"

Here is the working example of it, please have a look :

https://stackblitz.com/edit/angular-material2-checkbox-issue


Your demo with issue : https://stackblitz.com/edit/angular-material2-checkbox-issue-zyjhd3

Issues :

1) Missing let i =index; from *ngFor="let property of properties;let i =index;"

2) So was not passing correct value from here saveProperty($event, i)

3) this.properties[index][key] = property[key] , property[key] is string not boolean , so need to be converted to boolean

Solved : https://stackblitz.com/edit/angular-material2-checkbox-issue-tbutvp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM