Angular2 refreshing view on array push

后端 未结 2 971
遥遥无期
遥遥无期 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: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: `
        
    • {{line}}
    ` }) 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)) } } }

提交回复
热议问题