首页 > 解决方案 > Angular 没有通过 ChangeDetectorRef 运行变更检测

问题描述

我有一个带有输入变量的子组件,例如“名称”。它通过 Parent 组件的数据绑定具有一些初始值。现在,当我从子组件本身内部更改“名称”的值时,Angular 不知道。我如何让 Angular 知道这个变化?

根据我在网上阅读的内容,我尝试使用ChangeDetectorRef.detectChanges()ChangeDetectorRef.markForCheck()它似乎不起作用。我想我错过了一些东西。

这是此问题的 stackblitz 链接。如果您从子组件中更改名称,然后再次尝试从父组件更改名称,它不会更改,因为 Angular 仍然认为它绑定到父组件之前提供的值。但是我从子组件内部更改了它。我该如何解决?

标签: angularangular2-changedetection

解决方案


ngOnChanges

ngOnChanges 生命周期仅在有界输入属性值与当前值不同时运行

例子:

 OnChanges(changes: SimpleChanges){
   if(changes.name.currentValue !== changes.name.previousValue){
    //if the bound value is diffrent from currentValue then ngOnChanges will be triggered
  }

使用ngDoCheck生命周期钩子。

执行更改检测的回调方法,在默认更改检测器运行后调用。


推荐阅读