Why calling detectChanges() inside component doesn't update values, but wrapping code in setTimeout() does it?

后端 未结 2 670
情歌与酒
情歌与酒 2021-02-13 10:43

I\'m trying to automatically select the first value from set of options in

export class ExampleComponent implements OnI         


        
相关标签:
2条回答
  • 2021-02-13 11:09

    Watch out if you're using content projection (ng-content) or @HostBindings.

    When you run change detection for the component hosting the content, or setting the host binding it may not actually take effect because it is the parent component (which may be in a different module even) that 'owns' those attributes.

    However, the behavior related to markForCheck() was changed in May 2017 to mark for check the projected ng-content in the parent component. https://github.com/juleskremer/angular/commit/f894dbdd78cf463ed53b6c50d883326ff7fbff87

    It seems therefore that detectChanges() is insufficient for included content and you should use markForCheck instead which will trigger the included content to be checked.

    0 讨论(0)
  • 2021-02-13 11:20

    this.cdr.detectChanges() only runs change detection for the current component (and descendants). If setFirstItemActive() causes changes elsewhere this is not covered. setTimeout() or zone.run(...) or ApplicationRef.tick() causes change detection to be run for the whole application and therefore every binding is covered, not only the current component.

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