*ngFor Behaviour on primitive data type

a 夏天 提交于 2019-12-29 00:46:06

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/40863074/ngfor-behaviour-on-primitive-data-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!