在AngularJS中,您可以使用$scope$watch函数指定观察者来观察作用域变量的变化.什么等同于观察Angular 中的变量更改(例如,在组件变量中)?

推荐答案

在Angular 2中,变化检测是自动的...$scope.$watch()$scope.$digest()卢比.

不幸的是,开发指南的变更检测部分还没有编写(在Architecture Overview页的底部"其他内容"部分有一个占位符).

以下是我对变化检测的工作原理的理解:

  • 区js"monkey patches the world"——它拦截浏览器中的所有异步API(当Angular运行时).这就是为什么我们可以在组件中使用setTimeout()而不是像$timeout这样的东西...因为setTimeout()是猴子补的.
  • Angular建立并维护一棵"变化检测器"树.每个组件/指令都有一个这样的变化检测器(类).(您可以通过注入ChangeDetectorRef来访问此对象.)这些变化检测器是在Angular创建组件时创建的.它们会跟踪所有绑定的状态,以便进行脏判断.从某种意义上说,它们类似于Angular 1为{{}}个模板绑定设置的自动$watches()
    与Angular 1不同,更改检测图是一个有向树,不能有循环(这使得Angular 2的性能更高,我们将在下面看到).
  • 当事件触发(在Angular 区域内)时,我们编写的代码(事件处理程序回调)将运行.它可以更新它想要的任何数据--共享应用程序模型/状态和/或组件的视图状态.
  • After that, because of the hooks Zone.js added, it then runs Angular's change detection algorithm. By default (i.e., if you are not using the onPush change detection strategy on any of your components), every component in the tree is examined once (TTL=1)... from the top, in depth-first order. (Well, if you're in dev mode, change detection runs twice (TTL=2). See ApplicationRef.tick() for more about this.) It performs dirty checking on all of your bindings, using those change detector objects.
    • Lifecycle hooks are called as part of change detection.
      If the component data you want to watch is a primitive input property (String, boolean, number), you can implement ngOnChanges() to be notified of changes.
      If the input property is a reference type (object, array, etc.), but the reference didn't change (e.g., you added an item to an existing array), you'll need to implement ngDoCheck() (see this SO answer for more on this).
      You should only change the component's properties and/or properties of descendant components (because of the single tree walk implementation -- i.e., unidirectional data flow). Here's a plunker that violates that. Stateful pipes can also trip you up here.
  • 对于找到的任何绑定更改,都会更新组件,然后更新DOM.更改检测现已完成.
  • 浏览器会注意到DOM的更改并更新屏幕.

了解更多信息的其他参考资料:

Angular相关问答推荐

Angular 混合应用程序-模型未更新 Select

无法绑定到ngIf,因为它不是dis angular 17的已知属性

Angular 16未知参数:独立

NGX- colored颜色 Select 器安装出错

如何从URL中角下载图片?

Primeng:安装ANGLE 16.2.0版本

对REST后端的Angular/Priming过滤器请求导致无限循环

如何处理后端删除元素后元素列表的刷新

Angular 为什么延迟加载返回空路径?

Angular 按钮指令错误地附加子元素

Angular 15:在范围内提供相同标记时附加到提供的值

Angular 获取视频持续时间并存储在外部变量中

Angular 14 类型表单 - 数字控件的初始值

Angular 13 - 何时创建嵌入式视图?

当访问令牌在 MSAL for Angular 中过期时如何重定向用户?

如何在不刷新整页的情况下更新组件

Angular url加号转换为空格

交替行 colored颜色 angular material表

为什么 *ngIf 不适用于 ng-template?

没有 ChildrenOutletContexts 的提供者 (injectionError)