Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

angular - Change detection not registering data changes

I have an html structure with a component inside a component (forgot the proper word for it).

working basicly like this (largely simplified):

main html:

<div *ngFor="let item of data">
  <app-item [item]="item"></app-item>
</div>

<button (click)="addItem()">Add</button>

item html:

<div>{{item.name}}</div>

<button (click)="deleteItem()">Delete</button>

inside the app-item I display several items out of a list. The list gets it's data straight out of the database via an http.get request.

Now I also have functionality to add or delete items which both work (items get added or removed respectively to or from the database just fine). Though the change detection does not pick any of it up and the site needs to be refreshed (via F5 for example) to display the changes.

I checked the code (not all of it is from me) and couldn't find any specified change detection strategie.

I also tried to manually tigger change detection from the add and delete function via the ChangeDetectorRef (this.ref.detectChanges();). Though that also did not take away the need to manually refresh the page to see the changes.

Now what am I missing for change detection to pick this up? Or alternatively, how can I manually trigger it within my add/delete methods?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Since you are adding or deleting element in existing array angular is not able to pick the changes.

For this to work you can do like

  • assign array reference with new object of same elements of array as items= items.slice();
  • Or you can use Object.assign method as items= Object.assign([],items);
  • Both the things should be done after making changes to the array.

To manually fire change detection you can follow answer on this link

Inject ChangeDetectorRef in your component and then use detectChanges() method of that object to fire change detection manually.

constructure(private cd: ChangeDetectorRef) {}

someMethod() {
    this.cd.detectChanges();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...