Angular2 refreshing view on array push

后端 未结 2 970
遥遥无期
遥遥无期 2021-02-19 11:53

I can\'t seem to get angular2 view to be updated on an array.push function, called upon from a setInterval async operation.

the code is from this angular plunkr example

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

    The above code will work properly if "numberOfTicks" is just a number, but once I change it to an array and push data, it won't update. I can't seem to understand why is that.

    It is because a number is a JavaScript primitive type, and an array is a JavaScript reference type. When Angular change detection runs, it uses === to determine if a template binding has changed.

    If {{numberOfTicks}} is a primitive type, === compares the current and previous values. So the values 0 and 1 are different.

    If {{numberOfTicks}} is a reference type, === compares the current and previous (reference) values. So if the array reference didn't change, Angular won't detect a change. In your case, using push(), the array reference isn't changing.

    If you put the following in your template instead

    <div *ngFor="#tick of numberOfTicks">{{tick}}</div>
    

    then Angular would update the view because there is a binding to each array element, rather then just the array itself. So if a new item is push()ed, or an existing item is deleted or changed, all of these changes will be detected.

    So in your chart plunker, the following should update when the contents of the from and to arrays change:

    <span *ngFor="#item of from">{{item}}</span>
    <span *ngFor="#item of to">{{item}}</span>
    

    Well, it will update if each item is a primitive type.

    0 讨论(0)
  • 2021-02-19 12:46

    You need to update the whole reference of your array after adding an element in it:

      constructor(private ref: ChangeDetectorRef) {
        setInterval(() => {
          this.numberOfTicks.push(3);
          this.numberOfTicks = this.numberOfTicks.slice();
          this.ref.markForCheck();
        }, 1000);
      }
    }
    

    Edit

    The DoCheck interface could also interest you since it allows you to plug your own change detection algorithm.

    See this link for more details:

    • https://angular.io/docs/ts/latest/api/core/DoCheck-interface.html

    Here is a sample:

    @Component({
      selector: 'custom-check',
      template: `
        <ul>
          <li *ngFor="#line of logs">{{line}}</li>
        </ul>`
    })
    class CustomCheckComponent implements DoCheck {
      @Input() list: any[];
      differ: any;
      logs = [];
    
      constructor(differs: IterableDiffers) {
        this.differ = differs.find([]).create(null);
      }
    
      ngDoCheck() {
        var changes = this.differ.diff(this.list);
        if (changes) {
          changes.forEachAddedItem(r => this.logs.push('added ' + r.item));
          changes.forEachRemovedItem(r => this.logs.push('removed ' + r.item))
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题