Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
788 views
in Technique[技术] by (71.8m points)

angular - *ngFor Behaviour on primitive data type

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...