Angular未通过ChangeDetectorRef运行更改检测

Angular未通过ChangeDetectorRef运行更改检测,angular,angular2-changedetection,Angular,Angular2 Changedetection,我有一个子组件,输入变量为'name'。通过父组件的数据绑定,它有一些初始值。现在,当我从子组件内部更改“name”的值时,Angular不知道。我如何让Angular知道这一变化 根据我在网上读到的内容,我尝试使用ChangeDetectorRef.detectChanges()或ChangeDetectorRef.markForCheck()它似乎不起作用。我想我错过了什么 这是针对这个问题的stackblitz。如果您在子组件内更改名称,然后再次尝试从父组件更改名称,则不会更改,因为Ang

我有一个子组件,输入变量为'name'。通过父组件的数据绑定,它有一些初始值。现在,当我从子组件内部更改“name”的值时,Angular不知道。我如何让Angular知道这一变化

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


这是针对这个问题的stackblitz。如果您在子组件内更改名称,然后再次尝试从父组件更改名称,则不会更改,因为Angular仍然认为它已绑定到父组件先前提供的值。但我从子组件内部对其进行了更改。如何修复此问题?

您需要使用
ngOnChanges
生命周期挂钩来反映父组件到子组件中所做的更改

例如:

此外,在StackBiltz中,我可以看到您将
输入绑定如下:

<hello name="{{ name }}"></hello>
父组件:

 <hello [name]="name" (ChangeName)="name = $event"></hello>
 OnChanges(changes: SimpleChanges){
   if(changes.name.currentValue !== changes.name.previousValue){
    //if the bound value is diffrent from currentValue then ngOnChanges will be triggered
  }

您需要使用
ngOnChanges
生命周期挂钩来反映父组件到子组件中所做的更改

例如:

此外,在StackBiltz中,我可以看到您将
输入绑定如下:

<hello name="{{ name }}"></hello>
父组件:

 <hello [name]="name" (ChangeName)="name = $event"></hello>
 OnChanges(changes: SimpleChanges){
   if(changes.name.currentValue !== changes.name.previousValue){
    //if the bound value is diffrent from currentValue then ngOnChanges will be triggered
  }

要检测角度变化,您需要更改传递给输入的变量的参考。通过指定对象的副本,可以轻松触发更改

component.html


要检测角度变化,您需要更改传递给输入的变量的参考值。通过指定对象的副本,可以轻松触发更改

component.html


n改变

  onNameChangeClicked() {
    this.name = Object.assign('Angular from Parent ',{});
  }
仅当有界输入属性值与当前值不同时,ngOnChanges生命周期才会运行

示例:

 <hello [name]="name" (ChangeName)="name = $event"></hello>
 OnChanges(changes: SimpleChanges){
   if(changes.name.currentValue !== changes.name.previousValue){
    //if the bound value is diffrent from currentValue then ngOnChanges will be triggered
  }
使用ngDoCheck生命周期挂钩

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


ngOnChanges

  onNameChangeClicked() {
    this.name = Object.assign('Angular from Parent ',{});
  }
仅当有界输入属性值与当前值不同时,ngOnChanges生命周期才会运行

示例:

 <hello [name]="name" (ChangeName)="name = $event"></hello>
 OnChanges(changes: SimpleChanges){
   if(changes.name.currentValue !== changes.name.previousValue){
    //if the bound value is diffrent from currentValue then ngOnChanges will be triggered
  }
使用ngDoCheck生命周期挂钩

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


你的stackblitz链接不工作你的stackblitz链接不工作你能和我分享修改后的stackblitz吗?它似乎不起作用。此外,我还没有对父组件进行任何更改。我在父级不知道的子组件中进行了更改,因此当我单击时它不会更改值。嘿。。我无法在斯塔克比尔茨储蓄。你可以分享EMAIID,我会发送应用程序组件和hello组件CODEI,知道我们可以使用@输出,但是考虑一个场景,在这里我不想发出一个事件,那么我们怎样才能告诉角?改变从父的父代中的任何东西,输出是必要的。给我一个你不能发出事件的场景,你能和我分享修改后的stackblitz吗?它似乎不起作用。此外,我还没有对父组件进行任何更改。我在父级不知道的子组件中进行了更改,因此当我单击时它不会更改值。嘿。。我无法在斯塔克比尔茨储蓄。你可以分享EMAIID,我会发送应用程序组件和hello组件CODEI,知道我们可以使用@输出,但是考虑一个场景,在这里我不想发出一个事件,那么我们怎样才能告诉角?改变从父的父代中的任何东西,输出是必要的。给我一个你不能发出事件的场景作为例子