I have a list of objects which I am displaying using a *ngFor
on the HTML page. Now the user interacts with UI and changes one of the primitive values(boolean, from false to true).
As per my understanding the *ngFor
will only render the changes if the list object is modified completely i.e. removed and added again to the list. If I am right on this concept, then can you please suggest a method to reflect the change in the primitive type without re-initializing the component or modifying the object reference.
For Example:
<div *ngFor="let item of list">
<md-checkbox [(ngModel)]="item.selected"></md-checkbox>
</div>
User clicks on the checkbox, but the checkbox has to be ticked after certain validations from server. So let's say the checkbox needs to be unchecked and user gets a message on snack bar. So I loop through the list and modify item.selected
to false. But, the change is not reflected as i modified the primitive type selected(boolean) in the object item. So how to render the new value without reloading or initializing the page again.
Please let me know if more input is required.
If you use primitive values, you need trackBy
<div *ngFor="let item of list trackBy:trackByIdx">
<md-checkbox [(ngModel)]="item.selected"></md-checkbox>
</div>
trackByIdx(index: number, obj: any): any {
return index;
}
See also Angular2 NgFor inside tree model: wrong order when remove and then add elements
update according to the discussion below
Changing a boolean value bound by ngModel
when the input value is changed, may cause ngModel
not being updated. Adding an artificial change and callign detectChanges
can be used to work around.
constructor(private cdRef:ChangeDetectorRef) {}
deactivate(index: number) {
this.list[index][0] = true;
this.cdRef.detectChanges();
this.list[index][0] = false;
this.cdRef.detectChanges();
console.log(this.list);
}
Plunker example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With