Change detection not registering data changes

前端 未结 2 1040
陌清茗
陌清茗 2021-02-19 01:38

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:

相关标签:
2条回答
  • 2021-02-19 02:31

    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();
    }
    
    0 讨论(0)
  • 2021-02-19 02:31

    If you use a spread operator instead of push it should work.

    this.data = [...this.data, newItem];
    

    The reason for this is that angular detects a change when the whole object changes, or the reference changes, so a mutation isn't going to trigger it. So rather than mutating the array, you need to make it a new array.

    0 讨论(0)
提交回复
热议问题